import { createRegistration, setSessionCookie } from "@/modules/core/server/auth"; import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api"; function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } function readString(source: Record, key: string): string { const value = source[key]; return typeof value === "string" ? value.trim() : ""; } export async function POST(request: Request): Promise { const body = await readJsonBody(request); if (!isRecord(body)) { return jsonFailure("请求数据格式无效"); } const name = readString(body, "name"); const email = readString(body, "email"); const password = readString(body, "password"); const organizationId = readString(body, "organizationId"); if (!name || !email || !password) { return jsonFailure("姓名、邮箱和密码不能为空"); } if (password.length < 6) { return jsonFailure("密码至少需要6位"); } try { const created = await createRegistration({ name, email, password, organizationId: organizationId || undefined, }); if (created.session) { await setSessionCookie(created.session.id); } return jsonSuccess(organizationId ? "申请已提交,待机构管理员审批" : "账号已创建", { account: created.account, pendingApproval: !created.session, }); } catch (error) { const reason = error instanceof Error ? error.message : "账号创建失败"; const status = reason === "账号已存在" ? 409 : 500; return jsonFailure(reason, status); } }