import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { getSystemSettings, updateSystemSettings } from "@/modules/core/server/system-settings";

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() : "";
}

function readBoolean(source: Record<string, unknown>, key: string): boolean | null {
  const value = source[key];
  return typeof value === "boolean" ? value : null;
}

export async function GET(): Promise<Response> {
  const auth = await requirePermission("platform:manage", {
    action: "systemSettings.read",
    targetType: "systemSettings",
    targetId: "global",
  });

  if (!auth.success) {
    return auth.response;
  }

  const settings = await getSystemSettings();
  return jsonSuccess("系统配置已加载", { settings });
}

export async function PATCH(request: Request): Promise<Response> {
  const auth = await requirePermission("platform:manage", {
    action: "systemSettings.update",
    targetType: "systemSettings",
    targetId: "global",
  });

  if (!auth.success) {
    return auth.response;
  }

  const body = await readJsonBody(request);
  if (!isRecord(body)) {
    return jsonFailure("请求数据格式无效");
  }

  const registrationEnabled = "registrationEnabled" in body ? readBoolean(body, "registrationEnabled") : null;
  const oidcEnabled = "oidcEnabled" in body ? readBoolean(body, "oidcEnabled") : null;
  const oidcAutoProvision = "oidcAutoProvision" in body ? readBoolean(body, "oidcAutoProvision") : null;
  if ("registrationEnabled" in body && registrationEnabled === null) {
    return jsonFailure("注册开关无效");
  }
  if ("oidcEnabled" in body && oidcEnabled === null) {
    return jsonFailure("OIDC开关无效");
  }
  if ("oidcAutoProvision" in body && oidcAutoProvision === null) {
    return jsonFailure("OIDC自动开户配置无效");
  }

  const oidcIssuerUrl = readString(body, "oidcIssuerUrl");
  const oidcClientId = readString(body, "oidcClientId");
  if (oidcEnabled === true && (!oidcIssuerUrl || !oidcClientId)) {
    return jsonFailure("启用 OIDC 前请填写 Issuer URL 和 Client ID");
  }

  const settings = await updateSystemSettings({
    registrationEnabled: registrationEnabled ?? undefined,
    oidcEnabled: oidcEnabled ?? undefined,
    oidcIssuerUrl,
    oidcClientId,
    oidcClientSecret: readString(body, "oidcClientSecret"),
    oidcScopes: readString(body, "oidcScopes") || "openid profile email",
    oidcRedirectUri: readString(body, "oidcRedirectUri"),
    oidcAvatarClaim: readString(body, "oidcAvatarClaim") || "picture",
    oidcAutoProvision: oidcAutoProvision ?? undefined,
  });

  await recordAuditLog({
    actor: auth.context.account,
    action: "systemSettings.update",
    targetType: "systemSettings",
    targetId: settings.id,
    result: "success",
    reason: "更新全局系统配置",
  });

  return jsonSuccess("系统配置已保存", { settings });
}
