import { Capacitor } from '@capacitor/core';
import { GoogleAuth } from '@codetrix-studio/capacitor-google-auth';
import { LocalNotifications } from '@capacitor/local-notifications';
import { BACKEND_URL } from './backendEndpoint';

function rewriteUrls(obj: any, backendUrl: string): any {
  if (obj === null || obj === undefined) return obj;
  if (typeof obj === 'string') {
    if (obj.startsWith('/uploads/')) {
      return `${backendUrl}${obj}`;
    }
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map(item => rewriteUrls(item, backendUrl));
  }
  if (typeof obj === 'object') {
    const newObj: any = {};
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        newObj[key] = rewriteUrls(obj[key], backendUrl);
      }
    }
    return newObj;
  }
  return obj;
}

if (Capacitor.isNativePlatform()) {
  // Initialize native Google Login client to prevent NullPointerException crashes
  try {
    GoogleAuth.initialize({
      clientId: import.meta.env.VITE_GOOGLE_CLIENT_ID || '639044397050-7hair384u6lle941h033trut1s3q47l4.apps.googleusercontent.com',
      scopes: ['profile', 'email'],
      grantOfflineAccess: true,
    });
    console.log('[Native OAuth] GoogleAuth initialized successfully.');
  } catch (e) {
    console.error('[Native OAuth] Failed to initialize GoogleAuth client:', e);
  }

  // Request native local notification permission on startup
  try {
    LocalNotifications.requestPermissions().then(result => {
      console.log('[LocalNotifications] Permissions requested:', result);
    });
  } catch (e) {
    console.error('[LocalNotifications] Failed to request permissions:', e);
  }

  const backendUrl = BACKEND_URL;

  const originalFetch = window.fetch;
  window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
    let url = input;
    if (typeof url === 'string') {
      if (url.startsWith('/api/') || url.startsWith('/uploads/')) {
        url = `${backendUrl}${url}`;
      }
    } else if (url instanceof URL) {
      if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/uploads/')) {
        url = new URL(`${backendUrl}${url.pathname}${url.search}`);
      }
    } else if (url && typeof url === 'object' && 'url' in url) {
      // If it is a Request object
      const req = url as Request;
      const reqUrl = req.url;
      if (reqUrl.startsWith('/') || new URL(reqUrl).pathname.startsWith('/api/') || new URL(reqUrl).pathname.startsWith('/uploads/')) {
        const targetUrl = reqUrl.startsWith('/') ? `${backendUrl}${reqUrl}` : reqUrl.replace(new URL(reqUrl).origin, backendUrl);
        url = new Request(targetUrl, req);
      }
    }
    
    const response = await originalFetch(url, init);

    // Override the json method of this specific response instance
    const originalJson = response.json;
    response.json = async () => {
      const data = await originalJson.call(response);
      return rewriteUrls(data, backendUrl);
    };

    return response;
  };
}
