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

export async function POST(request: NextRequest) {
  try {
    await requireApiAuthWithOrg();
    const body = await request.json();
    const { provider: providerId, config } = body as {
      provider?: string;
      config?: Record<string, unknown>;
    };

    if (!providerId) {
      return NextResponse.json(
        { error: "Provider is required" },
        { status: 400 }
      );
    }

    const provider = getProvider(providerId);
    if (!provider) {
      return NextResponse.json(
        { error: "Unknown provider" },
        { status: 400 }
      );
    }

    const result = await provider.testConnection(config ?? {});
    return NextResponse.json({
      ok: result.success,
      message: result.message,
      error: result.success ? undefined : (result.message || "Connection failed"),
    });
  } catch (error) {
    return handleApiError(error);
  }
}
