diff --git a/routes/api/payments/cancel_auto_pay.ts b/routes/api/payments/cancel_auto_pay.ts new file mode 100644 index 0000000..0f36d30 --- /dev/null +++ b/routes/api/payments/cancel_auto_pay.ts @@ -0,0 +1,77 @@ +// routes/api/payments/cancel_auto_pay.ts +import { define } from "../../../utils.ts"; +import { cancelAutoPayment } from "../../../services/paymentService.ts"; +import { SessionCookie } from "../../auth/callback.ts"; + +export const handler = define.handlers({ + async POST(ctx) { + try { + const stateData: SessionCookie = ctx.state.data; + const user_id = stateData.user_id; + + if (!user_id) { + return new Response( + JSON.stringify({ + error: "User not authenticated", + }), + { + status: 401, + headers: { "Content-Type": "application/json" }, + }, + ); + } + + const contentType = ctx.req.headers.get("content-type") || ""; + let data: Record = {}; + + // Handle both JSON and form data + if (contentType.includes("application/json")) { + const jsonData = await ctx.req.json(); + data = jsonData; + } else { + const formData = await ctx.req.formData(); + data = { + lease_id: formData.get("lease_id")?.toString() || "", + }; + } + + const lease_id = 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 result = await cancelAutoPayment(lease_id, user_id); + + return new Response( + JSON.stringify({ + success: true, + lease: result[0], + }), + { + status: 200, + headers: { "Content-Type": "application/json" }, + }, + ); + } catch (e) { + console.error("Error canceling auto payment:", e); + return new Response( + JSON.stringify({ + error: e instanceof Error ? e.message : "Failed to cancel auto payment", + }), + { + status: 500, + headers: { "Content-Type": "application/json" }, + }, + ); + } + }, +});