import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import {
  ADMIN_COOKIE,
  decodeAdminToken,
  encodeAdminToken,
  verifyAdminCredentials,
} from "@/lib/admin-auth";
import { apiErrorResponse } from "@/lib/api-errors";
import { getOrCreateCorrelationId, withCorrelationId } from "@/lib/correlation-id";

export async function POST(req: NextRequest) {
  const correlationId = getOrCreateCorrelationId(req);
  const body = (await req.json().catch(() => null)) as {
    email?: string;
    password?: string;
  } | null;

  if (!body?.email || !body?.password) {
    return apiErrorResponse(400, "BAD_REQUEST", "email and password are required", correlationId);
  }

  const officer = verifyAdminCredentials(body.email, body.password);
  if (!officer) {
    return apiErrorResponse(401, "UNAUTHORIZED", "Invalid credentials", correlationId);
  }

  const token = encodeAdminToken(officer);
  const jar = await cookies();
  jar.set(ADMIN_COOKIE, token, {
    httpOnly: true,
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 8,
  });

  return withCorrelationId(NextResponse.json({ officer }), correlationId);
}

export async function DELETE() {
  const jar = await cookies();
  jar.delete(ADMIN_COOKIE);
  return NextResponse.json({ ok: true });
}

export async function GET(req: NextRequest) {
  const correlationId = getOrCreateCorrelationId(req);
  const jar = await cookies();
  const token = jar.get(ADMIN_COOKIE)?.value;
  const officer = decodeAdminToken(token);

  if (!officer) {
    return apiErrorResponse(401, "UNAUTHORIZED", "Not authenticated", correlationId);
  }

  return withCorrelationId(NextResponse.json({ officer }), correlationId);
}
