import { define, State } from "../../../utils.ts"; import { Context } from "fresh"; import { getUserPin as _getUserPin, setUserPin, } from "../../../services/userService.ts"; export const handler = define.handlers({ async POST(ctx: Context) { try { // Resolve user ID from authenticated state/session (cookie-backed) const userId = ctx.state.auth?.userId ?? ctx.state.data.user_id?.trim(); if (!userId) { return new Response( JSON.stringify({ error: "User not authenticated" }), { status: 401, headers: { "Content-Type": "application/json" }, }, ); } // Parse request body const body = await ctx.req.json(); const pin = typeof body?.pin === "string" ? body.pin.trim() : ""; // Validate required fields if (pin.length === 0) { return new Response( JSON.stringify({ error: "pin is required" }), { status: 400, headers: { "Content-Type": "application/json" }, }, ); } // Validate pin length (minimum 4 characters) if (pin.length < 4) { return new Response( JSON.stringify({ error: "Pin must be at least 4 characters long" }), { status: 400, headers: { "Content-Type": "application/json" }, }, ); } // Set user pin in database const userPin = await setUserPin(userId, pin); return new Response( JSON.stringify({ success: true, user_id: userPin.user_id, created_on: userPin.created_on, modified_on: userPin.modified_on, }), { status: 200, headers: { "Content-Type": "application/json" }, }, ); } catch (error) { console.error("Error setting user pin:", error); return new Response( JSON.stringify({ error: "Internal server error" }), { status: 500, headers: { "Content-Type": "application/json" }, }, ); } }, });