2026-02-14 02:20:19 +00:00

78 lines
2.1 KiB
TypeScript

// routes/api/retrieve/lease.ts
import { define } from "../../../utils.ts";
import { SessionCookie } from "../../auth/callback.ts";
import {
getLeasesByOwner,
getLeasesByTenant,
} from "../../../services/leaseService.ts";
import { getUser } from "../../../services/userService.ts";
import { Lease } from "../../../db/interfaces.ts";
export const handler = define.handlers({
async GET(ctx) {
try {
const stateData: SessionCookie = ctx.state.data;
const { user_id } = stateData;
if (!user_id) {
return new Response(
JSON.stringify({ error: "Unauthorized" }),
{
status: 401,
headers: { "Content-Type": "application/json" },
},
);
}
// Get user to determine role
const user = await getUser(user_id);
if (!user) {
return new Response(
JSON.stringify({ error: "User not found" }),
{
status: 404,
headers: { "Content-Type": "application/json" },
},
);
}
let leases: Lease[] = [];
// Filter leases based on user role
if (user.user_type === "landlord") {
// Landlord sees all leases where they are the owner
leases = await getLeasesByOwner(user_id);
} else if (user.user_type === "tenant") {
// Tenant sees only leases where they are the tenant
leases = await getLeasesByTenant(user_id);
} else {
// Admin or other roles - return empty or all (depending on requirements)
// For now, return empty list for non-landlord/tenant roles
leases = [];
}
return new Response(
JSON.stringify({
success: true,
leases,
count: leases.length,
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
},
);
} catch (error) {
console.error("Error fetching leases:", error);
return new Response(
JSON.stringify({ error: String(error) }),
{
status: 500,
headers: { "Content-Type": "application/json" },
},
);
}
},
});