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 POST(
  _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) {
      return NextResponse.json(
        { error: "Unknown provider" },
        { status: 400 }
      );
    }

    const configWithId = {
      ...(integration.config as Record<string, unknown>),
      _integrationId: integration.id,
    };
    const result = await provider.testConnection(configWithId);

    await prisma.integration.update({
      where: { id },
      data: {
        lastSyncStatus: result.success ? "connected" : "error",
        lastSyncAt: new Date(),
      },
    });

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