// routes/api/lease/approve.ts import { define } from "../../../utils.ts"; import { SessionCookie } from "../../auth/callback.ts"; import { approveLease, getLeaseById } from "../../../services/leaseService.ts"; import { getUserById } from "../../../services/userService.ts"; import { getPropertyById } from "../../../services/propertyService.ts"; import { sendLeaseApproved, } from "../../../services/notificationService.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 lease_id = (data.lease_id as string) || (data["lease_id"] as string); if (!lease_id) { return new Response( JSON.stringify({ error: "lease_id is required" }), { status: 400, headers: { "Content-Type": "application/json" }, }, ); } const lease = await getLeaseById(lease_id); if (!lease) { return new Response( JSON.stringify({ error: "Lease not found" }), { status: 404, headers: { "Content-Type": "application/json" }, }, ); } if (lease.owner_id !== user_id) { return new Response( JSON.stringify({ error: "Unauthorized: You do not own this lease" }), { status: 403, headers: { "Content-Type": "application/json" }, }, ); } const result = await approveLease(lease_id, user_id); if (!result || result.length === 0) { return new Response( JSON.stringify({ error: "Failed to approve lease" }), { status: 500, headers: { "Content-Type": "application/json" }, }, ); } const approvedLease = result[0]; if (lease.tenant_id) { const tenant = await getUserById(lease.tenant_id); const landlord = await getUserById(user_id); const property = lease.property_id ? await getPropertyById(lease.property_id) : null; await sendLeaseApproved(lease.tenant_id, { lease_id: lease.id, property_address: property?.address_1 ? `${property.address_1}, ${property.city}, ${property.state}` : lease.property_address || "Property", tenant_name: tenant?.name || "Tenant", landlord_name: landlord?.name || "Landlord", monthly_rent: property?.monthly_rent ?? lease.rent ?? undefined, }); } return new Response( JSON.stringify({ success: true, lease: approvedLease, lease: approvedLease, }), { status: 200, headers: { "Content-Type": "application/json" }, }, ); } catch (error) { console.error("Error approving lease:", error); return new Response( JSON.stringify({ error: String(error) }), { status: 500, headers: { "Content-Type": "application/json" }, }, ); } }, });