import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import { logout, parseSessionCookie, loadAdminSession, buildClearCookieHeader } from "@/lib/auth";
import { createAuditLog } from "@/lib/log";

export const runtime = "nodejs";

export async function POST(req: NextRequest) {
  try {
    const cookieHeader = req.headers.get("cookie");
    const sessionId = parseSessionCookie(cookieHeader);

    if (sessionId) {
      const session = await loadAdminSession(sessionId);
      if (session) {
        const ip = req.headers.get("x-forwarded-for") || req.headers.get("x-real-ip") || "unknown";
        const ua = req.headers.get("user-agent") || "unknown";
        await createAuditLog({
          userId: session.userId,
          username: session.username,
          action: "logout",
          resource: "auth",
          result: "success",
          ipAddress: ip,
          userAgent: ua,
        });
      }
      await logout(sessionId);
    }

    const response = NextResponse.json({ success: true });
    response.headers.set("Set-Cookie", buildClearCookieHeader());
    return response;
  } catch (e) {
    logError("Logout error:", e);
    const response = NextResponse.json({ success: false });
    response.headers.set("Set-Cookie", buildClearCookieHeader());
    return response;
  }
}
