import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth";

const OAUTH_CONFIGS: Record<
  string,
  { authUrl: string; clientIdEnv: string; scopes: string }
> = {
  planning_center: {
    authUrl: "https://api.planningcenteronline.com/oauth/authorize",
    clientIdEnv: "PCO_CLIENT_ID",
    scopes: "people",
  },
  google_sheets: {
    authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
    clientIdEnv: "GOOGLE_CLIENT_ID",
    scopes: "https://www.googleapis.com/auth/spreadsheets",
  },
};

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ provider: string }> }
) {
  try {
    const session = await auth();
    if (!session?.user?.orgId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { provider } = await params;
    const oauthConfig = OAUTH_CONFIGS[provider];
    if (!oauthConfig) {
      return NextResponse.json(
        { error: `OAuth not supported for provider: ${provider}` },
        { status: 400 }
      );
    }

    const clientId = process.env[oauthConfig.clientIdEnv];
    if (!clientId) {
      return NextResponse.json(
        {
          error: `${provider} OAuth not configured — set ${oauthConfig.clientIdEnv} in environment`,
        },
        { status: 400 }
      );
    }

    const integrationId = req.nextUrl.searchParams.get("integrationId") || "";
    const baseUrl = new URL(req.url).origin;
    const redirectUri = `${baseUrl}/api/integrations/oauth/${provider}/callback`;

    const state = Buffer.from(
      JSON.stringify({
        orgId: session.user.orgId,
        integrationId,
      })
    ).toString("base64url");

    const authUrl = new URL(oauthConfig.authUrl);
    authUrl.searchParams.set("client_id", clientId);
    authUrl.searchParams.set("redirect_uri", redirectUri);
    authUrl.searchParams.set("response_type", "code");
    authUrl.searchParams.set("scope", oauthConfig.scopes);
    authUrl.searchParams.set("state", state);

    if (provider === "google_sheets") {
      authUrl.searchParams.set("access_type", "offline");
      authUrl.searchParams.set("prompt", "consent");
    }

    return NextResponse.redirect(authUrl.toString());
  } catch (error) {
    console.error("[oauth/authorize] error:", error);
    return NextResponse.json(
      { error: "OAuth authorization failed" },
      { status: 500 }
    );
  }
}
