/**
 * Get the base URL for internal API calls
 * Works in both development and production environments
 */
export function getBaseUrl(request?: Request): string {
  // In production (Firebase/Vercel), use the request origin
  if (request && typeof window === 'undefined') {
    const origin = request.headers.get('origin') || request.headers.get('referer');
    if (origin) {
      return new URL(origin).origin;
    }
  }
  
  // Check environment variables
  if (process.env.NEXT_PUBLIC_APP_URL) {
    return process.env.NEXT_PUBLIC_APP_URL;
  }
  
  if (process.env.VERCEL_URL) {
    return `https://${process.env.VERCEL_URL}`;
  }
  
  // Default to localhost for development
  return 'http://localhost:3000';
}

/**
 * Get the full API URL for internal API calls
 */
export function getApiUrl(path: string, request?: Request): string {
  const baseUrl = getBaseUrl(request);
  const cleanPath = path.startsWith('/') ? path : `/${path}`;
  return `${baseUrl}${cleanPath}`;
}

