// routes/api/lease/request-approval.ts import { define } from "../../../utils.ts"; import { page } from "fresh"; import { SessionCookie } from "../../auth/callback.ts"; import { requestLeaseApproval, getLeaseById, } from "../../../services/leaseService.ts"; import { getTenantInviteById, updateTenantInvite, } from "../../../services/tenantInviteService.ts"; import { getPropertyById } from "../../../services/propertyService.ts"; export const handler = define.handlers({ async POST(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" }, }, ); } const contentType = ctx.req.headers.get("content-type") || ""; let data: Record = {}; if (contentType.includes("application/json")) { data = await ctx.req.json(); } else { const formData = await ctx.req.formData(); for (const [key, value] of formData.entries()) { data[key] = typeof value === "string" ? value : String(value); } } const invite_id = (data.invite_id as string) || (data["invite_id"] as string); const property_id = (data.property_id as string) || (data["property_id"] as string); if (!invite_id || !property_id) { return new Response( JSON.stringify({ error: "invite_id and property_id are required", }), { status: 400, headers: { "Content-Type": "application/json" }, }, ); } const invite = await getTenantInviteById(invite_id); if (!invite) { return new Response( JSON.stringify({ error: "Invite not found" }), { status: 404, headers: { "Content-Type": "application/json" }, }, ); } const property = await getPropertyById(property_id); if (!property) { return new Response( JSON.stringify({ error: "Property not found" }), { status: 404, headers: { "Content-Type": "application/json" }, }, ); } const leaseResult = await requestLeaseApproval( user_id, property_id, invite_id, ); if (!leaseResult || leaseResult.length === 0) { return new Response( JSON.stringify({ error: "Failed to create lease request" }), { status: 500, headers: { "Content-Type": "application/json" }, }, ); } const lease = leaseResult[0]; await updateTenantInvite(invite_id, { lease_id: lease.id }); return new Response( JSON.stringify({ success: true, lease, }), { status: 200, headers: { "Content-Type": "application/json" }, }, ); } catch (error) { console.error("Error requesting lease approval:", error); return new Response( JSON.stringify({ error: String(error) }), { status: 500, headers: { "Content-Type": "application/json" }, }, ); } }, });