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

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

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

  try {
    const result = await loginWithPassword({ email, password });
    await setSessionCookie(result.session.id);
    return jsonSuccess("登录成功", { account: result.account });
  } catch (error) {
    await recordAuditLog({
      action: "account.login",
      targetType: "account",
      result: "failure",
      reason: `登录失败：${email}`,
    });
    const reason = error instanceof Error ? error.message : "登录失败";
    return jsonFailure(reason, 401);
  }
}
