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

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { validateStaffSession } from "@/lib/staff-session";
import { randomBytes } from "crypto";
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 },
    });

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

    // Generate a secure random token
    const token = `mawidi_${randomBytes(32).toString("hex")}`;

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

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

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

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