/**
 * GET /api/auth/oauth/[provider]
 * Initiates the OAuth flow — builds authorization URL and redirects the user.
 */

import { NextResponse } from "next/server";
import {
  isValidProvider,
  generateOAuthState,
  buildAuthorizationUrl,
  OAUTH_PROVIDERS,
} from "@/lib/oauth";
import { oauthLimiter, getLimiterKey, tooManyRequests } from "@/lib/ratelimit";

export async function GET(
  req: Request,
  { params }: { params: Promise<{ provider: string }> }
) {
  // ── Rate limiting ──────────────────────────────────────────────────────────
  const limitKey = getLimiterKey(req, "oauth-init");
  const limit    = oauthLimiter.check(limitKey);
  if (!limit.allowed) return tooManyRequests(limit.resetIn);

  const { provider } = await params;

  if (!isValidProvider(provider)) {
    return NextResponse.json({ error: `Unknown provider: ${provider}` }, { status: 400 });
  }

  // ── Verify provider is configured ─────────────────────────────────────────
  const config = OAUTH_PROVIDERS[provider];
  if (!config.clientId() || !config.clientSecret()) {
    return NextResponse.json(
      { error: `${config.name} OAuth is not configured on this server.` },
      { status: 503 }
    );
  }

  // ── Generate state and redirect ────────────────────────────────────────────
  const state    = await generateOAuthState(provider);
  const authUrl  = buildAuthorizationUrl(provider, state);

  return NextResponse.redirect(authUrl);
}
