import { createRegistration, setSessionCookie } from "@/modules/core/server/auth";
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function readString(source: Record<string, unknown>, key: string): string {
  const value = source[key];
  return typeof value === "string" ? value.trim() : "";
}

export async function POST(request: Request): Promise<Response> {
  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");
  const invitationToken = readString(body, "invitationToken");

  if (!name || !email || !password) {
    return jsonFailure("姓名、邮箱和密码不能为空");
  }

  if (password.length < 6) {
    return jsonFailure("密码至少需要6位");
  }

  try {
    const created = await createRegistration({
      name,
      email,
      password,
      organizationId: organizationId || undefined,
      invitationToken: invitationToken || undefined,
    });
    if (created.session) {
      await setSessionCookie(created.session.id);
    }
    return jsonSuccess(organizationId && !invitationToken ? "账号已创建，机构加入申请已提交" : "账号已创建", {
      account: created.account,
      pendingApproval: false,
    });
  } catch (error) {
    const reason = error instanceof Error ? error.message : "账号创建失败";
    const status = reason === "账号已存在" ? 409 : 500;
    return jsonFailure(reason, status);
  }
}
