import { NextResponse } from "next/server";

import {
  createAdminSessionValue,
  getAdminSession,
  getAdminSessionCookieName,
  getAdminSessionCookieOptions,
} from "@/lib/admin/adminAuth";
import { countAdminUsers, getAdminUserById, normalizeAdminId, verifyPassword } from "@/lib/admin/adminUsersDb";

export const runtime = "nodejs";

export async function GET(req: Request) {
  const session = getAdminSession(req);
  if (session) return NextResponse.json({ authenticated: true, id: session.id });

  const users = await countAdminUsers();
  return NextResponse.json({ authenticated: false, bootstrapRequired: users === 0 });
}

export async function POST(req: Request) {
  let payload: any;
  try {
    payload = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid payload." }, { status: 400 });
  }

  let id = "";
  try {
    id = normalizeAdminId(String(payload?.id || ""));
  } catch (err: any) {
    return NextResponse.json({ error: err?.message || "Invalid admin id." }, { status: 400 });
  }
  const password = String(payload?.password || "");
  if (!id || !password) {
    return NextResponse.json({ error: "Missing id or password." }, { status: 400 });
  }

  const adminUser = await getAdminUserById(id);
  if (!adminUser) {
    const users = await countAdminUsers();
    if (users === 0) {
      return NextResponse.json(
        { error: "No admin user configured. Create the first admin account.", bootstrapRequired: true },
        { status: 409 }
      );
    }
    return NextResponse.json({ error: "Invalid credentials." }, { status: 401 });
  }

  if (!verifyPassword(password, adminUser.passwordSalt, adminUser.passwordHash)) {
    return NextResponse.json({ error: "Invalid credentials." }, { status: 401 });
  }

  const value = createAdminSessionValue(id);
  const res = NextResponse.json({ ok: true, authenticated: true, id });
  res.cookies.set(getAdminSessionCookieName(), value, getAdminSessionCookieOptions());
  return res;
}
