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

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

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

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 organization = readString(body, "organization");

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

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

  try {
    await ensureSystemDefaults();
    const created = await setupFirstPlatformAdmin({ organization, name, email, password });
    await setSessionCookie(created.session.id);
    return jsonSuccess("初始化完成", { account: created.account });
  } catch (error) {
    const reason = error instanceof Error ? error.message : "初始化失败";
    const status = reason === "系统已完成初始化" ? 409 : 500;
    return jsonFailure(reason, status);
  }
}
