import { NextRequest, NextResponse } from "next/server";
import { getAdminSession, extractRawToken } from "@/lib/admin/auth";
import { db, hashToken, AuditLocation } from "@/lib/admin/db";

export const dynamic = "force-dynamic";

/**
 * POST /api/admin/security/location
 * Sets or updates the location state for the current admin session.
 * Stores in MongoDB session record and returns cookie.
 */
export async function POST(req: NextRequest) {
  try {
    const ctx = await getAdminSession(req);
    if (!ctx) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await req.json().catch(() => ({}));
    const status =
      body.status === "available" || body.status === "denied" || body.status === "unavailable"
        ? body.status
        : "unavailable";

    const location: AuditLocation = {
      status,
      latitude: typeof body.latitude === "number" ? body.latitude : undefined,
      longitude: typeof body.longitude === "number" ? body.longitude : undefined,
      address: typeof body.address === "string" ? body.address : undefined,
      locality: typeof body.locality === "string" ? body.locality : undefined,
      city: typeof body.city === "string" ? body.city : undefined,
      region: typeof body.region === "string" ? body.region : undefined,
      country: typeof body.country === "string" ? body.country : undefined,
      postalCode: typeof body.postalCode === "string" ? body.postalCode : undefined,
      source: typeof body.source === "string" ? body.source : "browser-geolocation",
      capturedAt: typeof body.capturedAt === "string" ? body.capturedAt : new Date().toISOString(),
    };

    const rawToken = await extractRawToken(req);
    if (rawToken) {
      const tokenHash = hashToken(rawToken);
      await db.updateSessionLocation(tokenHash, location);
    }

    const res = NextResponse.json({ success: true, location });
    // Set admin_loc cookie so server operations can read it
    res.cookies.set("admin_loc", encodeURIComponent(JSON.stringify(location)), {
      path: "/",
      httpOnly: false,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      maxAge: 60 * 60 * 24, // 24 hours
    });

    return res;
  } catch (error) {
    console.error("[POST /api/admin/security/location] Error:", error);
    return NextResponse.json(
      { error: (error as Error).message || "Internal server error" },
      { status: 500 }
    );
  }
}
