/**
 * GET /api/auth/google
 * ----------------------
 * Starts the Google OAuth flow. Redirects the user to Google's
 * consent screen where they grant meSEO access to their GA4/GSC/GBP data.
 *
 * Query params:
 *   ?brandId=xxx&service=ga4  (which brand and which integration)
 *
 * After the user approves, Google redirects back to /api/auth/google/callback
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";

export const dynamic = "force-dynamic";

// Must match the client_id used by the cron's refreshGoogleAccessToken —
// both read from the same env var so refresh_tokens are always issued and
// redeemed by the same OAuth client. A hardcoded fallback here would cause
// invalid_grant on every cron refresh because the token would be bound to
// a different client_id than what the cron uses.
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID || "";

// Scopes for each service
const SERVICE_SCOPES: Record<string, string[]> = {
  ga4: ["https://www.googleapis.com/auth/analytics.readonly"],
  gsc: ["https://www.googleapis.com/auth/webmasters.readonly"],
  gbp: ["https://www.googleapis.com/auth/business.manage"],
};

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId") ?? "";
  const service = searchParams.get("service") ?? "ga4";

  const scopes = SERVICE_SCOPES[service] ?? SERVICE_SCOPES.ga4;

  // Build the callback URL — use NEXT_PUBLIC_APP_URL for consistency with Google's authorized URIs
  const appUrl = process.env.NEXT_PUBLIC_APP_URL || new URL(req.url).origin;
  const redirectUri = `${appUrl}/auth/google/callback`;

  // State parameter: encode brandId + service so the callback knows what to do
  const state = Buffer.from(JSON.stringify({ brandId, service })).toString("base64url");

  const params = new URLSearchParams({
    client_id: GOOGLE_CLIENT_ID,
    redirect_uri: redirectUri,
    response_type: "code",
    scope: scopes.join(" "),
    access_type: "offline",       // gets a refresh token
    // Always show the account picker AND re-prompt for scope consent.
    // `consent` alone re-shows the scope approval screen but Google
    // silently uses whichever account is currently signed in, so
    // users who wanted to reconnect with a different Google account
    // ended up bound to the same one. `select_account` forces the
    // picker on every OAuth start. The two values are combined
    // space-separated per RFC 6749 / Google's docs.
    prompt: "select_account consent",
    // `include_granted_scopes` lets Google do incremental auth when
    // the user later connects a second service (GSC after GA4, etc.)
    // without re-asking for the scopes they already granted.
    include_granted_scopes: "true",
    state,
  });

  const googleAuthUrl = `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;

  return NextResponse.redirect(googleAuthUrl);
}
