import { NextRequest, NextResponse } from "next/server";
import { auth, clerkClient } from "@clerk/nextjs/server";
import { getAuthContext } from "@/lib/auth/context";
import log from "@/lib/logger";

/**
 * DELETE /api/invitations/[id]
 *
 * Revoke a pending invitation (creator-only permission)
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const { userId } = await auth();
    if (!userId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id: invitationId } = await params;
    const authContext = await getAuthContext();

    // Fetch pending invitations to find and verify the one being revoked
    const client = await clerkClient();
    const invitationList = await client.invitations.getInvitationList({
      status: "pending",
    });

    // Find the invitation
    const invitation = invitationList.data.find(
      (inv) => inv.id === invitationId,
    );

    if (!invitation) {
      return NextResponse.json(
        { error: "Invitation not found or already processed" },
        { status: 404 },
      );
    }

    const metadata = invitation.publicMetadata as any;
    const invitationGymId =
      (metadata?.gymId as string | null | undefined) ?? null;
    const createdBy = (metadata?.createdBy as string | undefined) ?? undefined;

    const canManageByRole =
      authContext.role === "superAdmin" ||
      (authContext.role === "admin" &&
        authContext.gymId !== null &&
        invitationGymId === authContext.gymId);

    // Check if current user created this invitation
    if (createdBy !== userId && !canManageByRole) {
      return NextResponse.json(
        {
          error:
            "Forbidden - You can only cancel invitations you created or manage within your scope",
        },
        { status: 403 },
      );
    }

    // Revoke the invitation
    await client.invitations.revokeInvitation(invitationId);

    log.info("Invitation revoked", {
      invitationId,
      revokedBy: userId,
      email: invitation.emailAddress,
    });

    return NextResponse.json({
      data: { success: true },
    });
  } catch (error) {
    log.error("DELETE /api/invitations/[id] error:", error);
    return NextResponse.json(
      { error: "Failed to revoke invitation" },
      { status: 500 },
    );
  }
}
