// apps/web/lib/fetch.ts

const BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';

export async function fetchWithAuth(url: string, options: RequestInit = {}): Promise<Response> {
  let token = null;

  if (typeof window !== 'undefined') {
    // Extract access_token directly from document.cookie parsing
    const match = document.cookie.match(/(^|;)\s*access_token\s*=\s*([^;]+)/);
    if (match) {
      token = decodeURIComponent(match[2]);
    }
    
    // Fallback to localStorage just in case of future cross-env updates
    if (!token || token === 'undefined' || token === 'null') {
      token = localStorage.getItem('access_token') || localStorage.getItem('token');
    }

    if (token === 'undefined' || token === 'null') {
      token = null;
    }
  }

  const mergedHeaders: Record<string, string> = {};
  
  if (options.headers) {
    if (options.headers instanceof Headers) {
      options.headers.forEach((value, key) => {
        mergedHeaders[key] = value;
      });
    } else if (Array.isArray(options.headers)) {
      options.headers.forEach(([key, value]) => {
        mergedHeaders[key] = value;
      });
    } else {
      Object.assign(mergedHeaders, options.headers);
    }
  }

  if (token) {
    mergedHeaders['Authorization'] = `Bearer ${token}`;
  }

  // Redirect backend-implemented endpoints directly to Express API (port 3001)
  let targetUrl = url;
  if (url.startsWith('/')) {
    // Database-direct Next.js routes (e.g., /api/admin/users, /api/admin/properties, /api/admin/packages, /api/settings/branding, /api/properties/[id]/verify)
    // should remain local, while backend routes are mapped to BASE_URL.
    const backendPrefixes = [
      '/api/admin/bookings',
      '/api/admin/subscriptions',
      '/api/admin/submissions',
      '/api/admin/properties/scrape',
      '/api/admin/properties/scrape-and-save',
      '/api/admin/seo',
      '/api/seo',
    ];
    const isBackendRoute = backendPrefixes.some(prefix => url.startsWith(prefix));
    
    if (isBackendRoute) {
      const baseUrlNormalized = BASE_URL.endsWith('/') ? BASE_URL.slice(0, -1) : BASE_URL;
      targetUrl = `${baseUrlNormalized}${url}`;
    }
  }

  // Ensure internal API routes explicitly forward credentials if proxying
  return fetch(targetUrl, {
    ...options,
    credentials: 'include',
    headers: mergedHeaders,
  });
}

/**
 * Save token consistently — call this from login page after successful auth.
 * Writes to both localStorage AND cookie for maximum compatibility.
 */
export function saveAuthToken(token: string, user?: any): void {
  if (typeof window === 'undefined') return;
  localStorage.setItem('access_token', token);
  document.cookie = `access_token=${encodeURIComponent(token)}; path=/; max-age=${30 * 24 * 60 * 60}; SameSite=Lax`;
  if (user) {
    localStorage.setItem('user', JSON.stringify(user));
    if (user.role) localStorage.setItem('userRole', String(user.role));
  }
}

/**
 * Clear all auth data — call this from logout handler.
 */
export function clearAuthToken(): void {
  if (typeof window === 'undefined') return;
  ['access_token', 'token', 'authToken', 'jwt', 'user', 'userRole'].forEach(k => {
    localStorage.removeItem(k);
    sessionStorage.removeItem(k);
  });
  document.cookie = 'access_token=; path=/; max-age=0';
  document.cookie = 'token=; path=/; max-age=0';
}
