/**
 * Staff API: User Integration Settings
 * GET /api/staff/users/[id]/integrations - Get user's integration config
 * PATCH /api/staff/users/[id]/integrations - Update user's integration config
 */

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 GET(
  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 });
    }

    // Integration data is on the users model (n8nWebhookToken, voiceAgentId).
    // These fields are not yet in Convex users table, so always read from Prisma.
    // When DS_ORGANIZATIONS=convex, we still read from Prisma for user-level fields.
    const _ds = getDataSource("organizations");
    void _ds;

    const user = await prisma.users.findUnique({
      where: { id },
      select: {
        id: true,
        n8nWebhookToken: true,
        voiceAgentId: true,
        voiceAgentConfig: true,
      },
    });

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

    return NextResponse.json({
      integrations: {
        n8nWebhookToken: user.n8nWebhookToken,
        voiceAgentId: user.voiceAgentId,
        voiceAgentConfig: user.voiceAgentConfig,
      },
    });
  } catch (error) {
    console.error("[Staff API] Failed to fetch user integrations:", error);
    return NextResponse.json(
      { error: "Failed to fetch integration settings" },
      { status: 500 },
    );
  }
}

export async function PATCH(
  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 body = await request.json();
    const { voiceAgentId, voiceAgentConfig } = body;

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

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

    // Update user integrations (always Prisma -- user model fields)
    const updatedUser = await prisma.users.update({
      where: { id },
      data: {
        voiceAgentId: voiceAgentId || null,
        voiceAgentConfig: voiceAgentConfig || null,
      },
      select: {
        id: true,
        voiceAgentId: true,
        voiceAgentConfig: true,
      },
    });

    return NextResponse.json({
      success: true,
      integrations: {
        voiceAgentId: updatedUser.voiceAgentId,
        voiceAgentConfig: updatedUser.voiceAgentConfig,
      },
    });
  } catch (error) {
    console.error("[Staff API] Failed to update user integrations:", error);
    return NextResponse.json(
      { error: "Failed to update integration settings" },
      { status: 500 },
    );
  }
}
