import { NextResponse } from "next/server";
import { createWordPressIntegration, testWordPressConnection } from "@/lib/integrations/wordpress";

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as {
      siteUrl?: string;
      username?: string;
      applicationPassword?: string;
    };

    const result = await testWordPressConnection({
      siteUrl: body.siteUrl ?? "",
      username: body.username ?? "",
      applicationPassword: body.applicationPassword ?? "",
    });

    if (!result.ok) {
      return NextResponse.json({ ok: false, error: result.error }, { status: 400 });
    }

    const integration = createWordPressIntegration(
      {
        siteUrl: body.siteUrl ?? "",
        username: body.username ?? "",
        applicationPassword: body.applicationPassword ?? "",
      },
      result,
    );

    return NextResponse.json({
      ok: true,
      integration: {
        ...integration,
        applicationPassword: undefined,
      },
      applicationPassword: integration.applicationPassword,
      siteName: result.siteName,
      adminUrl: result.adminUrl,
    });
  } catch {
    return NextResponse.json({ ok: false, error: "Connection test failed." }, { status: 500 });
  }
}
