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

export async function GET() {
  try {
    const session = await requireApiAuthWithOrg();

    const integrations = await prisma.integration.findMany({
      where: { organizationId: session.user.orgId },
      orderBy: { createdAt: "desc" },
    });

    const providers = getAllProviders().map((p) => ({
      id: p.id,
      name: p.name,
      description: p.description,
      icon: p.icon,
      category: p.category,
      supportsOAuth: p.supportsOAuth,
      supportsFieldMapping: p.supportsFieldMapping,
      configFields: p.configFields,
      setupGuide: p.setupGuide,
    }));

    return NextResponse.json({ integrations, providers });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function POST(req: NextRequest) {
  try {
    const session = await requireApiAuthWithPermission("integrations.manage");

    const body = await req.json();
    const { provider, name, config, fieldMapping, triggerEvents } = body;

    if (!provider || !name) {
      return NextResponse.json(
        { error: "Provider and name are required" },
        { status: 400 }
      );
    }

    const integration = await prisma.integration.create({
      data: {
        organizationId: session.user.orgId,
        provider,
        name,
        config: config || {},
        fieldMapping: fieldMapping || null,
        triggerEvents: triggerEvents || ["card_reviewed"],
        enabled: false,
      },
    });

    return NextResponse.json({ integration });
  } catch (error) {
    return handleApiError(error);
  }
}
