import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getProvider } from "@/lib/integrations/registry";
import {
  requireApiAuthWithPermission,
  handleApiError,
} from "@/lib/api-auth";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await requireApiAuthWithPermission("integrations.manage");

    const { id } = await params;
    const integration = await prisma.integration.findFirst({
      where: { id, organizationId: session.user.orgId },
    });

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

    const provider = getProvider(integration.provider);
    if (!provider?.getExternalFields) {
      return NextResponse.json({ fields: [] });
    }

    const configWithId = {
      ...(integration.config as Record<string, unknown>),
      _integrationId: integration.id,
    };
    const fields = await provider.getExternalFields(configWithId);
    return NextResponse.json({ fields });
  } catch (error) {
    return handleApiError(error);
  }
}
