import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { prisma } from "@/lib/db";
import { revokeSession } from "@/lib/services/session-manager";
import { getAuthenticatedUser } from "@/lib/auth-helpers";
import { getIPFromRequest } from "@/lib/geolocation";

export async function POST(request: NextRequest) {
  try {
    const cookieStore = cookies();
    const authToken = cookieStore.get("auth_token")?.value;
    const staffToken = cookieStore.get("staff-session")?.value;
    const nextAuthToken =
      cookieStore.get("next-auth.session-token")?.value ||
      cookieStore.get("__Secure-next-auth.session-token")?.value;

    const sessionToken = authToken || staffToken || nextAuthToken || null;
    const authResult = await getAuthenticatedUser(request);
    const userIdFromAuth = authResult?.user?.id;

    // Find matching session record (if any)
    const sessionRecord = sessionToken
      ? await prisma.user_sessions.findFirst({
          where: { token: sessionToken },
          select: { id: true, userId: true },
        })
      : null;

    if (sessionRecord) {
      await revokeSession(sessionRecord.id, sessionRecord.userId);
      // Audit logout for traffic analytics
      const ip = await getIPFromRequest(request);
    } else if (userIdFromAuth) {
      // Still log logout intent even if session record missing
      const ip = await getIPFromRequest(request);
    }

    const response = NextResponse.json({ success: true });

    // Clear cookies regardless of record presence (idempotent)
    response.cookies.set("auth_token", "", { maxAge: 0, path: "/" });
    response.cookies.set("staff-session", "", { maxAge: 0, path: "/" });
    response.cookies.set("next-auth.session-token", "", {
      maxAge: 0,
      path: "/",
    });
    response.cookies.set("__Secure-next-auth.session-token", "", {
      maxAge: 0,
      path: "/",
    });

    return response;
  } catch (error) {
    console.error("Logout error:", error);
    return NextResponse.json(
      { success: false, error: "Logout failed" },
      { status: 500 },
    );
  }
}
