/**
 * Network Interception Script
 * 
 * This script runs in the PAGE context (not content script context)
 * to intercept network requests and extract tokens.
 * 
 * Injected via script.src to bypass CSP restrictions.
 */

(function() {
  // Immediate log to verify script runs
  console.log('[Filevine Plugin] Network interception script executing (page context)');
  
  try {
    // Intercept fetch - check both requests and responses
    const originalFetch = window.fetch;
    window.fetch = async function(...args) {
      const url = typeof args[0] === 'string' ? args[0] : args[0]?.url || args[0]?.href;
      const options = typeof args[0] === 'object' && !args[0]?.url ? args[0] : args[1] || {};
      
            // Check for Authorization header in outgoing requests
            if (options.headers) {
              // Handle Headers object
              let authHeader = null;
              if (options.headers.get) {
                authHeader = options.headers.get('Authorization');
              } else if (options.headers.Authorization) {
                authHeader = options.headers.Authorization;
              } else if (options.headers.authorization) {
                authHeader = options.headers.authorization;
              }
              
              if (authHeader && authHeader.startsWith('Bearer ')) {
                const token = authHeader.substring(7);
                console.log('[Filevine Plugin] ✅ Found Authorization header in fetch request!', url);
                window.postMessage({
                  type: 'FV_PLUGIN_TOKEN',
                  token: token,
                  expiresIn: 3600
                }, '*');
              }
              
              // Log all headers for Filevine API requests
              if (url && url.includes('filevineapp.com') && !url.includes('pendo.io')) {
                console.log('[Filevine Plugin] Fetch request to Filevine:', url);
                if (options.headers instanceof Headers) {
                  for (const [key, val] of options.headers.entries()) {
                    if (key.toLowerCase().includes('auth') || key.toLowerCase().startsWith('x-fv-')) {
                      console.log(`[Filevine Plugin] Fetch header: ${key} = ${val.substring(0, 50)}...`);
                    }
                  }
                } else {
                  Object.keys(options.headers).forEach(key => {
                    if (key.toLowerCase().includes('auth') || key.toLowerCase().startsWith('x-fv-')) {
                      console.log(`[Filevine Plugin] Fetch header: ${key} = ${options.headers[key].substring(0, 50)}...`);
                    }
                  });
                }
              }
            }
      
      const response = await originalFetch.apply(this, args);
      const responseUrl = response.url || url;
      
      // Check response for token endpoints
      if (responseUrl && (
        responseUrl.includes('connect/token') || 
        responseUrl.includes('identity.filevine.com') ||
        responseUrl.includes('/token')
      )) {
        console.log('[Filevine Plugin] Token endpoint detected:', responseUrl);
        try {
          const clone = response.clone();
          const data = await clone.json();
          if (data.access_token) {
            console.log('[Filevine Plugin] Token found in response!');
            window.postMessage({
              type: 'FV_PLUGIN_TOKEN',
              token: data.access_token,
              expiresIn: data.expires_in
            }, '*');
          }
        } catch (e) {
          // Try text if JSON fails
          try {
            const text = await response.clone().text();
            const data = JSON.parse(text);
            if (data.access_token) {
              console.log('[Filevine Plugin] Token found in text response!');
              window.postMessage({
                type: 'FV_PLUGIN_TOKEN',
                token: data.access_token,
                expiresIn: data.expires_in
              }, '*');
            }
          } catch (e2) {
            console.log('[Filevine Plugin] Could not parse token response:', e2);
          }
        }
      }
      return response;
    };
    
    // Intercept XMLHttpRequest
    const originalOpen = XMLHttpRequest.prototype.open;
    const originalSend = XMLHttpRequest.prototype.send;
    const originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
    
    // Store headers to check later
    XMLHttpRequest.prototype._fvHeaders = {};
    
    XMLHttpRequest.prototype.open = function(method, url, ...rest) {
      this._fvUrl = url;
      this._fvHeaders = {};
      return originalOpen.call(this, method, url, ...rest);
    };
    
    // Intercept setRequestHeader to capture Authorization headers
    XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
      // Log all headers for Filevine API requests (for debugging)
      if (this._fvUrl && this._fvUrl.includes('filevineapp.com') && !this._fvUrl.includes('pendo.io')) {
        const headerValue = typeof value === 'string' ? value.substring(0, 100) : String(value);
        console.log(`[Filevine Plugin] Header set: ${name} = ${headerValue}${value.length > 100 ? '...' : ''}`);
      }
      
      if (name.toLowerCase() === 'authorization' && value.startsWith('Bearer ')) {
        const token = value.substring(7);
        console.log('[Filevine Plugin] ✅ Found Authorization header via setRequestHeader!', this._fvUrl);
        window.postMessage({
          type: 'FV_PLUGIN_TOKEN',
          token: token,
          expiresIn: 3600
        }, '*');
      }
      
      // Also check for x-fv-* headers (they might contain tokens or IDs)
      if (name.toLowerCase().startsWith('x-fv-')) {
        console.log(`[Filevine Plugin] Filevine header: ${name} = ${value.substring(0, 50)}...`);
      }
      
      this._fvHeaders[name.toLowerCase()] = value;
      return originalSetRequestHeader.call(this, name, value);
    };
    
    XMLHttpRequest.prototype.send = function(...args) {
      // Check stored headers for Authorization
      const authHeader = this._fvHeaders['authorization'];
      if (authHeader && authHeader.startsWith('Bearer ')) {
        const token = authHeader.substring(7);
        console.log('[Filevine Plugin] Found Authorization header in XHR send!', this._fvUrl);
        window.postMessage({
          type: 'FV_PLUGIN_TOKEN',
          token: token,
          expiresIn: 3600
        }, '*');
      }
      
      // Also log all headers for debugging
      if (this._fvUrl && this._fvUrl.includes('filevineapp.com')) {
        console.log('[Filevine Plugin] XHR request to Filevine:', this._fvUrl);
        console.log('[Filevine Plugin] Headers:', Object.keys(this._fvHeaders));
      }
      
      // Check for token endpoint responses
      if (this._fvUrl && (
        this._fvUrl.includes('connect/token') || 
        this._fvUrl.includes('identity.filevine.com') ||
        this._fvUrl.includes('/token')
      )) {
        console.log('[Filevine Plugin] XHR token endpoint detected:', this._fvUrl);
        this.addEventListener('load', function() {
          try {
            const data = JSON.parse(this.responseText);
            if (data.access_token) {
              console.log('[Filevine Plugin] Token found in XHR response!');
              window.postMessage({
                type: 'FV_PLUGIN_TOKEN',
                token: data.access_token,
                expiresIn: data.expires_in
              }, '*');
            }
          } catch (e) {
            console.log('[Filevine Plugin] XHR token parse error:', e);
          }
        });
      }
      return originalSend.apply(this, args);
    };
    
    // Also intercept WebSocket connections (they sometimes have tokens in URL)
    // NOTE: WebSocket tokens are usually for specific services (like discussions),
    // not the main API. We'll capture it but prioritize API tokens.
    const originalWebSocket = window.WebSocket;
    window.WebSocket = function(url, protocols) {
      if (url.includes('access_token') || url.includes('token=')) {
        const tokenMatch = url.match(/[?&](?:access_token|token)=([^&]+)/);
        if (tokenMatch && tokenMatch[1]) {
          const token = decodeURIComponent(tokenMatch[1]);
          console.log('[Filevine Plugin] Found token in WebSocket URL (may be service-specific):', url.substring(0, 100));
          // Only send if it's not a discussions WebSocket (those use different tokens)
          if (!url.includes('discussions')) {
            window.postMessage({
              type: 'FV_PLUGIN_TOKEN',
              token: token,
              expiresIn: 3600
            }, '*');
          } else {
            console.log('[Filevine Plugin] Skipping discussions WebSocket token (not main API token)');
          }
        }
      }
      return new originalWebSocket(url, protocols);
    };
    
    console.log('[Filevine Plugin] Network interception active (page context)');
  } catch (error) {
    console.error('[Filevine Plugin] Failed to setup interception:', error);
  }
})();
