/**
 * Staff API: Revoke N8N Webhook Token
 * POST /api/staff/users/[id]/integrations/revoke-token
 */

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { validateStaffSession } from "@/lib/staff-session";
import { getDataSource } from "@/lib/data-source";

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const { id } = await params;

    const staffSession = await validateStaffSession(request);
    if (!staffSession.valid) {
      return NextResponse.json({ error: staffSession.error }, { status: 401 });
    }

    const existingUser = await prisma.users.findUnique({
      where: { id },
      select: { id: true, email: true, n8nWebhookToken: true },
    });

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

    if (!existingUser.n8nWebhookToken) {
      return NextResponse.json(
        { error: "No token to revoke" },
        { status: 400 },
      );
    }

    // Convex branch -- also revoke in Convex integrations table
    if (getDataSource("organizations") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        await convexMutation("organizations/mutations:revokeApiToken", {
          userId: id,
        });
      } catch (convexError) {
        console.error(
          "Convex token revocation failed, continuing with Prisma:",
          convexError,
        );
      }
    }

    // Always update Prisma (user model field)
    await prisma.users.update({
      where: { id },
      data: { n8nWebhookToken: null },
    });

    console.log(
      `[Staff API] Revoked N8N token for user ${existingUser.email} by staff ${staffSession.user?.username}`,
    );

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