import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/admin/db";
import { requireAuth, getClientMetadata } from "@/lib/admin/auth";
import { formatLocationDisplay } from "@/lib/admin/location-formatter";

export const dynamic = "force-dynamic";

/**
 * GET /api/admin/sessions
 * Returns the active sessions registry for the currently authenticated Admin.
 * Automatically reconciles stale sessions before returning results.
 */
export async function GET(req: NextRequest) {
  try {
    const { user, session: currentSession } = await requireAuth(req);

    // Fetch strictly active sessions with automatic stale reconciliation
    const activeSessions = await db.getActiveSessionsForUser(user.id, 120);

    const mappedSessions = activeSessions.map((s) => {
      const isCurrent = s.tokenHash === currentSession.tokenHash || s.id === currentSession.id;
      return {
        id: s.id,
        browser: s.browser || "Web Browser",
        browserVersion: s.browserVersion || null,
        operatingSystem: s.operatingSystem || "Unknown OS",
        deviceType: s.deviceType || "Desktop",
        deviceSummary: s.device || `${s.browser || "Browser"} on ${s.operatingSystem || "Device"}`,
        ipAddress: s.ipAddress,
        createdAt: s.createdAt,
        lastSeenAt: s.lastSeenAt || s.lastActiveAt || s.createdAt,
        locationDisplay: formatLocationDisplay(s.location),
        rawLocation: s.location || null,
        networkSecurity: s.networkSecurity
          ? {
              isVpn: s.networkSecurity.isVpn,
              isProxy: s.networkSecurity.isProxy,
              isTor: s.networkSecurity.isTor,
              isRelay: s.networkSecurity.isRelay,
              isBlocked: s.networkSecurity.isBlocked,
              provider: s.networkSecurity.provider,
            }
          : null,
        status: s.status || "ACTIVE",
        isCurrent,
      };
    });

    // Sort: Current device first, then descending by lastSeenAt
    mappedSessions.sort((a, b) => {
      if (a.isCurrent) return -1;
      if (b.isCurrent) return 1;
      return new Date(b.lastSeenAt).getTime() - new Date(a.lastSeenAt).getTime();
    });

    const response = NextResponse.json({
      sessions: mappedSessions,
      activeCount: mappedSessions.length,
      currentSessionId: currentSession.id,
    });

    // Cache security: strictly private and non-cached
    response.headers.set("Cache-Control", "private, no-cache, no-store, must-revalidate");
    return response;
  } catch (error) {
    const status = (error as unknown as { status: number }).status || 500;
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Failed to fetch active sessions" },
      { status }
    );
  }
}

/**
 * DELETE /api/admin/sessions?id=[sessionId]
 * Revokes a specific individual active session.
 */
export async function DELETE(req: NextRequest) {
  try {
    const { user, session: currentSession } = await requireAuth(req);
    const { ip, userAgent, location } = getClientMetadata(req);

    const { searchParams } = new URL(req.url);
    const sessionId = searchParams.get("id");

    if (!sessionId) {
      return NextResponse.json({ error: "Session ID parameter 'id' is required." }, { status: 400 });
    }

    // Prohibit revoking current session via this endpoint (must use regular sign out)
    if (sessionId === currentSession.id) {
      return NextResponse.json(
        { error: "Cannot revoke current session here. Use Sign Out to end this session." },
        { status: 400 }
      );
    }

    const revoked = await db.revokeSessionById(sessionId, user.id, user.email, "ADMIN_REVOKED");
    if (!revoked) {
      return NextResponse.json(
        { error: "Session not found or already inactive." },
        { status: 404 }
      );
    }

    // Security audit log
    await db.logSecurityEvent({
      actorId: user.id,
      actorName: user.name,
      actorEmail: user.email,
      actorLevel: user.level,
      targetUserId: user.id,
      targetUserEmail: user.email,
      targetUserName: user.name,
      action: "SESSION_REVOKED",
      details: {
        revokedSessionId: sessionId,
        reason: "ADMIN_REVOKED",
        note: "Admin revoked individual session from Profile",
      },
      ipAddress: ip,
      userAgent,
      location: location || currentSession.location,
    });

    return NextResponse.json({
      ok: true,
      message: "Session successfully signed out.",
    });
  } catch (error) {
    const status = (error as unknown as { status: number }).status || 500;
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Failed to revoke session" },
      { status }
    );
  }
}
