import type { Request } from 'express';

const CALLBACK_PATH = '/api/auth/google/callback';

function stripTrailingSlashes(url: string): string {
  return url.replace(/\/+$/, '');
}

function originFromRequest(req: Request): string {
  const forwardedProto = (req.headers['x-forwarded-proto'] as string | undefined)
    ?.split(',')[0]
    ?.trim();
  const protocol = forwardedProto || req.protocol || 'http';

  const forwardedHost = (req.headers['x-forwarded-host'] as string | undefined)
    ?.split(',')[0]
    ?.trim();
  const host =
    forwardedHost || req.get('host') || `localhost:${process.env.PORT || '3002'}`;

  return `${protocol}://${host}`;
}

/**
 * Exact `redirect_uri` for Google OAuth (and Passport callbackURL).
 * Must match an entry in Google Cloud Console → OAuth client → Authorized redirect URIs.
 *
 * Priority:
 * 1. GOOGLE_CALLBACK_URL — full URL (recommended in production)
 * 2. API_PUBLIC_URL — origin only, path is appended
 * 3. HOST_PRODUCTION — origin only (when NODE_ENV=production), path appended; matches server.ts banner host
 * 4. BASE_URL — origin only, path is appended
 * 5. If `req` is passed — origin from request (needs trust proxy behind HTTPS reverse proxy).
 *    Note: Passport registers GoogleStrategy once without `req`; use env (1–5) in production
 *    so the auth URL and Passport share the same `redirect_uri` (avoids redirect_uri_mismatch).
 * 6. http://localhost:{PORT}/api/auth/google/callback
 *
 * Example (API on subdomain + port): set in `.env` and in Google Cloud “Authorized redirect URIs”
 * the exact same value, e.g. `https://api.quickconnectnow.co:5513/api/auth/google/callback`
 * — not the marketing site `https://quickconnectnow.co/...` unless that URL reverse-proxies to this API.
 */
export function resolveGoogleOAuthCallbackUrl(req?: Request): string {
  const explicit = process.env.GOOGLE_CALLBACK_URL?.trim();
  if (explicit) {
    return stripTrailingSlashes(explicit);
  }

  const hostProduction =
    process.env.NODE_ENV === 'production'
      ? process.env.HOST_PRODUCTION?.trim()
      : undefined;

  const publicOrigin =
    process.env.API_PUBLIC_URL?.trim() ||
    hostProduction ||
    process.env.BASE_URL?.trim();
  if (publicOrigin) {
    return `${stripTrailingSlashes(publicOrigin)}${CALLBACK_PATH}`;
  }

  if (req) {
    return `${originFromRequest(req)}${CALLBACK_PATH}`;
  }

  const port = process.env.PORT || '3002';
  return `http://localhost:${port}${CALLBACK_PATH}`;
}
