import { NextRequest, NextResponse } from "next/server";
import { scryptSync, timingSafeEqual } from "crypto";
import { createAdminClient } from "@/lib/supabase/server";
import { verifyTotp } from "@/lib/auth/totp";
import { createSessionCookie, COOKIE_NAME, SESSION_TTL_SECONDS } from "@/lib/auth/session";

function verifyPassword(password: string, stored: string): boolean {
  // stored format: "<salt-hex>:<hash-hex>", hash = scrypt(password, salt)
  const [saltHex, hashHex] = stored.split(":");
  if (!saltHex || !hashHex) return false;
  const derived = scryptSync(password, Buffer.from(saltHex, "hex"), 64);
  const stored_ = Buffer.from(hashHex, "hex");
  return derived.length === stored_.length && timingSafeEqual(derived, stored_);
}

export async function POST(req: NextRequest) {
  const { email, password, totpCode } = await req.json();
  if (!email || !password || !totpCode) {
    return NextResponse.json({ error: "Missing fields" }, { status: 400 });
  }

  const supabase = createAdminClient();
  const { data: admin } = await supabase
    .from("admin_users")
    .select("id, password_hash, totp_secret")
    .eq("email", email)
    .single();

  // Constant-shape response whether or not the email exists, to avoid
  // leaking which admin emails are registered.
  if (!admin || !verifyPassword(password, admin.password_hash)) {
    return NextResponse.json({ error: "Invalid credentials" }, { status: 401 });
  }
  if (!admin.totp_secret || !verifyTotp(admin.totp_secret, totpCode)) {
    return NextResponse.json({ error: "Invalid 2FA code" }, { status: 401 });
  }

  const res = NextResponse.json({ ok: true });
  res.cookies.set(COOKIE_NAME, createSessionCookie(admin.id), {
    httpOnly: true,
    secure: true,
    sameSite: "lax",
    maxAge: SESSION_TTL_SECONDS,
    path: "/",
  });
  return res;
}
