/**
 * Session Revocation API
 * DELETE - Revoke a specific session
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { withCSRF } from "@/lib/csrf";
import { withRateLimit } from "@/lib/rate-limiter";
import { getUserSessions, revokeSession } from "@/lib/services/session-manager";
import { getIPFromRequest, getLocationFromIP } from "@/lib/geolocation";
import { convexMutation } from "@/lib/convex-client";
import { getAuthenticatedConvexUser } from "@/lib/convex-auth-state";

/**
 * DELETE /api/user/sessions/[id]
 * Revokes a specific session (except current session)
 * Rate limited to 20 requests per 15 minutes
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const { id: sessionIdParam } = await params;
    const session = await auth();

    if (!session?.user?.email) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    // Rate limiting
    const rateLimitResponse = await applyRateLimit(
      request,
      rateLimiters.authGeneral,
    );
    if (rateLimitResponse) return rateLimitResponse;

    // CSRF protection
    if (!validateCSRFToken(request)) {
      return NextResponse.json(
        { success: false, error: "Invalid CSRF token" },
        { status: 403 },
      );
    }

    // Get user from Convex
    const user = await convexQuery<ConvexUser>("auth/queries:getUserByEmail", {
      email: session.user.email,
    });

    if (!user) {
      return NextResponse.json(
        { success: false, error: "User not found" },
        { status: 404 },
      );
    }

    const sessionId = sessionIdParam as Id<"user_sessions">;

    // Verify the session ID belongs to this user by checking all user sessions
    const allSessions =
      (await convexQuery<ConvexUserSession[]>("auth/queries:listUserSessions", {
        userId: user._id,
      })) ?? [];

    const targetSession = allSessions.find((s) => s._id === sessionId);

    if (!targetSession) {
      return NextResponse.json(
        { success: false, error: "Session not found" },
        { status: 404 },
      );
    }

    // Prevent revoking current session
    const currentToken = session.user.id;
    if (targetSession.token === currentToken) {
      return NextResponse.json(
        {
          success: false,
          error: "Cannot revoke your current session. Use logout instead.",
        },
        { status: 400 },
      );
    }

    // Revoke the session by deleting it from Convex
    await convexMutation("auth/mutations:deleteSession", {
      id: sessionId,
    });

    // Audit log
    const ipAddress = await getIPFromRequest(request);
    const locationData = await getLocationFromIP(ipAddress);

    await convexMutation("auth/mutations:createAuditLog", {
      userId: user.id,
      type: "security",
      action: "session_revoked",
      success: true,
      ip: ipAddress,
      userAgent: request.headers.get("user-agent") || "",
      metadata: {
        revokedSessionId: sessionId,
        revokedDevice: targetSession.deviceName,
        location: locationData,
      },
    });

    return NextResponse.json({
      success: true,
      message: "Session revoked successfully",
    });
  } catch (error) {
    console.error("[API] Failed to revoke session:", error);
    return NextResponse.json(
      { success: false, error: "Failed to revoke session" },
      { status: 500 },
    );
  }
}
