import { canManageUsers, loadManagedUsers } from "@/lib/auth/user-management"; import { requireApiUser } from "@/lib/auth/guard"; import { parseNewUser } from "@/lib/auth/user-input"; import { pbAdmin } from "@/lib/pb"; import { authMode } from "@/lib/auth/session"; export const dynamic = "force-dynamic"; export async function GET(): Promise { if (authMode() !== "users") return Response.json({ error: "Not found" }, { status: 404 }); const actor = await requireApiUser("dashboard"); if (actor instanceof Response) return actor; if (!canManageUsers(actor)) return Response.json({ error: "Not allowed" }, { status: 403 }); const pb = await pbAdmin(); const { users, sites } = await loadManagedUsers(pb, actor); return Response.json({ users, sites }); } export async function POST(request: Request): Promise { if (authMode() !== "users") return Response.json({ error: "Not found" }, { status: 404 }); const actor = await requireApiUser("dashboard"); if (actor instanceof Response) return actor; if (!canManageUsers(actor)) return Response.json({ error: "Not allowed" }, { status: 403 }); let body: unknown; try { body = await request.json(); } catch { return Response.json({ error: "Invalid user details" }, { status: 400 }); } if (actor.role === "site_user" && (!body || typeof body !== "object" || (body as Record).role !== "clock_only")) { return Response.json({ error: "Site managers can only add clock users" }, { status: 403 }); } const pb = await pbAdmin(); const sites = await pb.collection("sites").getFullList({ fields: "id" }); const payload = parseNewUser(body, new Set(sites.filter((site) => actor.role === "admin" || actor.siteIds.includes(site.id)).map((site) => site.id))); if (!payload) return Response.json({ error: "Enter a valid email, name, role, password, and site selection" }, { status: 400 }); try { const created = await pb.collection("users").create(payload); return Response.json({ user: { id: created.id, email: payload.email, name: payload.name, role: payload.role, sites: payload.sites, is_active: true, must_change_password: true, modules: payload.modules, all_sites: payload.all_sites, } }, { status: 201 }); } catch (error) { const code = (error as { response?: { data?: { email?: { code?: string } } } })?.response?.data?.email?.code; return Response.json({ error: code === "validation_not_unique" ? "This email is already in use" : "Could not create user" }, { status: code === "validation_not_unique" ? 409 : 500, }); } }