import {
  createSession,
  createSessionCookie,
  ensureInitialSuperAdmin,
  normalizeUsername,
  requestUsesHttps,
  verifyPassword,
} from "../../../../lib/user-auth";
import { getRawDb } from "../../../../lib/mvp-db";

export async function POST(request: Request) {
  try {
    await ensureInitialSuperAdmin();
    const body = (await request.json()) as { username?: string; password?: string };
    const username = normalizeUsername(body.username);
    const password = String(body.password ?? "");
    const user = await getRawDb()
      .prepare(
        `SELECT id, username, role, password_hash, password_salt, password_iterations
         FROM users WHERE username = ? LIMIT 1`,
      )
      .bind(username)
      .first<{
        id: string;
        username: string;
        role: string;
        password_hash: string;
        password_salt: string;
        password_iterations: number;
      }>();
    if (!user || !(await verifyPassword(password, user))) {
      return Response.json({ error: "账号或密码错误" }, { status: 401 });
    }
    const token = await createSession(user.id);
    const secure = requestUsesHttps(request);
    return Response.json(
      { user: { id: user.id, username: user.username, role: user.role } },
      { headers: { "Set-Cookie": createSessionCookie(token, secure) } },
    );
  } catch (error) {
    return Response.json(
      { error: error instanceof Error ? error.message : "登录失败" },
      { status: 500 },
    );
  }
}
