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

export async function POST(req: NextRequest) {
  try {
    const rawToken = await extractRawToken(req);
    const authCtx = await getAdminSession(req);
    const { ip, userAgent, location } = getClientMetadata(req);

    if (rawToken) {
      const tokenHash = hashToken(rawToken);
      await db.revokeSession(tokenHash, authCtx?.user.email || "USER", "USER_LOGOUT");
    }

    if (authCtx) {
      await db.logSecurityEvent({
        actorId: authCtx.user.id,
        actorName: authCtx.user.name,
        actorEmail: authCtx.user.email,
        actorLevel: authCtx.user.level,
        targetUserId: authCtx.user.id,
        targetUserEmail: authCtx.user.email,
        targetUserName: authCtx.user.name,
        action: "SESSION_LOGOUT",
        details: {
          sessionId: authCtx.session.id,
          browser: authCtx.session.browser,
          browserVersion: authCtx.session.browserVersion,
          operatingSystem: authCtx.session.operatingSystem,
          deviceType: authCtx.session.deviceType,
          reason: "USER_LOGOUT",
          note: "Admin user logged out deliberately",
        },
        ipAddress: ip || authCtx.session.ipAddress,
        location: location || authCtx.session.location,
        networkSecurity: authCtx.session.networkSecurity,
        userAgent: userAgent || authCtx.session.userAgent,
      });
    }

    await clearSessionCookie();

    const res = NextResponse.json({ ok: true, message: "Logged out successfully." });
    res.cookies.set("quto_admin_session", "", {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      path: "/",
      maxAge: 0,
      expires: new Date(0),
    });
    res.headers.set("Cache-Control", "no-store, no-cache, must-revalidate");
    return res;
  } catch (error) {
    console.error("[api/admin/auth/logout] Error:", error);
    await clearSessionCookie();
    const res = NextResponse.json({ ok: true });
    res.cookies.set("quto_admin_session", "", {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      path: "/",
      maxAge: 0,
      expires: new Date(0),
    });
    res.headers.set("Cache-Control", "no-store, no-cache, must-revalidate");
    return res;
  }
}
