import { eq } from "drizzle-orm";

import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { getCurrentAuthContext, toPublicAccount } from "@/modules/core/server/auth";
import { getDatabase } from "@/modules/core/server/db";
import { accounts } from "@/modules/core/server/schema";

export const dynamic = "force-dynamic";

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 PATCH(request: Request): Promise<Response> {
  const context = await getCurrentAuthContext();
  if (!context) {
    return jsonFailure("未登录或会话已过期", 401);
  }

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

  const name = readString(body, "name");
  const avatarUrl = readString(body, "avatarUrl");

  if (!name) {
    return jsonFailure("用户名称不能为空");
  }

  const database = getDatabase();
  const rows = await database
    .update(accounts)
    .set({
      name,
      avatarUrl,
      updatedAt: new Date(),
    })
    .where(eq(accounts.id, context.account.id))
    .returning();
  const account = rows[0];
  if (!account) {
    return jsonFailure("账号不存在", 404);
  }

  const publicAccount = toPublicAccount(account, context.account.role, context.organization);

  await recordAuditLog({
    actor: publicAccount,
    organizationId: context.organization?.id,
    action: "account.profile.update",
    targetType: "account",
    targetId: publicAccount.id,
    result: "success",
    reason: "更新个人资料",
  });

  return jsonSuccess("用户资料已保存", { account: publicAccount });
}
