/**
 * Cookie Interceptor
 * 
 * Intercepts ASP.NET Application Cookies from Filevine requests.
 * Since these are HTTP-only cookies, we need to use Chrome's webRequest API
 * to capture them when they're sent.
 * 
 * NOTE: Filevine's web app uses cookies, but the API needs Bearer tokens.
 * We need to find a way to exchange the cookie for a Bearer token, or
 * check if the API also accepts cookies.
 */

import { MESSAGE_TYPES, API_BASE_URL, ENDPOINTS } from '../lib/constants.js';
import { authManager } from './auth.js';
import { webApiClient } from './web-api-client.js';

let lastCookieValue = null;

/**
 * Intercept cookies from webRequest API
 * This captures cookies from outgoing requests to Filevine
 * 
 * NOTE: Cookies are not available in requestHeaders - we need to use chrome.cookies API
 */
export function setupCookieInterceptor() {
  console.log('[Cookie Interceptor] Setting up cookie interception...');
  
  // Use chrome.cookies API to read cookies directly
  // This is more reliable than trying to intercept from request headers
  checkCookies();
  
  // Also set up periodic checking
  setInterval(checkCookies, 5000); // Check every 5 seconds
  
  // Listen for cookie changes
  chrome.cookies.onChanged.addListener((changeInfo) => {
    if (changeInfo.cookie.domain.includes('filevineapp.com')) {
      console.log('[Cookie Interceptor] Cookie changed:', changeInfo.cookie.name);
      if (changeInfo.cookie.name.includes('ApplicationCookie')) {
        checkCookies();
      }
    }
  });
  
  // Also listen for Set-Cookie headers in responses (backup method)
  chrome.webRequest.onHeadersReceived.addListener(
    (details) => {
      if (!details.url.includes('filevineapp.com')) {
        return;
      }

      const setCookieHeaders = details.responseHeaders?.filter(
        h => h.name.toLowerCase() === 'set-cookie'
      );

      if (setCookieHeaders && setCookieHeaders.length > 0) {
        for (const header of setCookieHeaders) {
          if (header.value.includes('.AspNet.ApplicationCookie=')) {
            console.log('[Cookie Interceptor] Set-Cookie header detected, checking cookies...');
            // Trigger cookie check
            setTimeout(checkCookies, 100);
          }
        }
      }
    },
    {
      urls: ['https://*.filevineapp.com/*']
    },
    ['responseHeaders']
  );
}

/**
 * Check cookies using chrome.cookies API
 */
async function checkCookies() {
  try {
    // Get all cookies for Filevine domains
    const cookies = await chrome.cookies.getAll({
      domain: 'filevineapp.com'
    });
    
    // Find ASP.NET Application Cookie
    const appCookie = cookies.find(c => c.name === '.AspNet.ApplicationCookie');
    const cookieC1 = cookies.find(c => c.name === '.AspNet.ApplicationCookieC1');
    const cookieC2 = cookies.find(c => c.name === '.AspNet.ApplicationCookieC2');
    
    if (appCookie) {
      // Build full cookie string (ASP.NET uses chunked cookies)
      let fullCookieValue = appCookie.value;
      if (cookieC1) fullCookieValue += cookieC1.value;
      if (cookieC2) fullCookieValue += cookieC2.value;
      
      // Build full cookie header format
      let cookieHeader = `.AspNet.ApplicationCookie=${appCookie.value}`;
      if (cookieC1) cookieHeader += `; .AspNet.ApplicationCookieC1=${cookieC1.value}`;
      if (cookieC2) cookieHeader += `; .AspNet.ApplicationCookieC2=${cookieC2.value}`;
      
      // Only process if cookie changed
      if (appCookie.value !== lastCookieValue) {
        lastCookieValue = appCookie.value;
        console.log('[Cookie Interceptor] ✅ Found ASP.NET cookie!');
        console.log('[Cookie Interceptor] Cookie preview:', appCookie.value.substring(0, 50) + '...');
        console.log('[Cookie Interceptor] Cookie domain:', appCookie.domain);
        
        // Store cookie for potential API use
        chrome.storage.session.set({
          'fv_cookie': cookieHeader,
          'fv_cookie_value': appCookie.value,
          'fv_cookie_timestamp': Date.now()
        });
        
        // Try to exchange cookie for Bearer token
        attemptTokenExchange(cookieHeader).catch(err => {
          console.log('[Cookie Interceptor] Token exchange failed (expected):', err.message);
        });
      }
    } else {
      // Debug: log when no cookie found
      if (cookies.length > 0) {
        console.log('[Cookie Interceptor] Found cookies but no ASP.NET cookie:', cookies.map(c => c.name).join(', '));
      }
    }
  } catch (error) {
    console.error('[Cookie Interceptor] Error checking cookies:', error);
  }
}

/**
 * Attempt to use cookies with the API
 * 
 * IMPORTANT DISCOVERY: Filevine has TWO different APIs:
 * 1. Web app API: product.filevineapp.com/api/... (uses cookies) ✅
 * 2. External API: api.filevineapp.com/fv-app/v2/... (needs Bearer tokens) ❓
 * 
 * We need to check if the external API also accepts cookies, or if we need Bearer tokens.
 */
async function attemptTokenExchange(cookieString) {
  // First, try the EXTERNAL API with cookies
  // This is what our extension needs to use
  try {
    console.log('[Cookie Interceptor] Testing external API with cookies...');
    const response = await fetch(`${API_BASE_URL}${ENDPOINTS.GET_USER_ORGS}`, {
      method: 'POST',
      headers: {
        'Cookie': cookieString,
        'Content-Type': 'application/json'
      },
      credentials: 'include'
    });

    if (response.ok) {
      console.log('[Cookie Interceptor] ✅ External API accepts cookies!');
      const data = await response.json();
      
      // Send to auth manager to process
      chrome.runtime.sendMessage({
        type: 'cookie_auth_success',
        data: data,
        cookie: cookieString
      });
      
      return data;
    } else {
      const errorText = await response.text();
      console.log('[Cookie Interceptor] External API does not accept cookies, status:', response.status);
      console.log('[Cookie Interceptor] Error:', errorText.substring(0, 200));
    }
  } catch (error) {
    console.log('[Cookie Interceptor] External API test error:', error.message);
  }
  
  // Try the WEB APP API with cookies (we know this works from Network tab)
  // This might give us user info we can use
  try {
    console.log('[Cookie Interceptor] Testing web app API with cookies...');
    const response = await fetch('https://product.filevineapp.com/api/orgs', {
      method: 'GET',
      headers: {
        'Cookie': cookieString,
        'Content-Type': 'application/json'
      },
      credentials: 'include'
    });

    if (response.ok) {
      console.log('[Cookie Interceptor] ✅ Web app API accepts cookies!');
      const data = await response.json();
      console.log('[Cookie Interceptor] Web app API response:', JSON.stringify(data).substring(0, 200));
      
      // Extract org info from web app API response
      if (data.success && data.data && data.data.length > 0) {
        const org = data.data[0];
        console.log('[Cookie Interceptor] Found org:', org.name, 'ID:', org.id);
        console.log('[Cookie Interceptor] Org ownerID (user ID):', org.ownerID);
        
        // Store cookie and org info for use with web app API
        chrome.storage.session.set({
          'fv_cookie': cookieString,
          'fv_org_id': String(org.id),
          'fv_org_name': org.name,
          'fv_user_id': String(org.ownerID || org.ownerId), // Store user ID from org
          'fv_using_web_api': true, // Flag to use web app API instead of external API
          'fv_cookie_timestamp': Date.now()
        });
        
        // Call auth manager directly (we're in the same context)
        authManager.processCookieAuth({
          orgId: String(org.id),
          orgName: org.name,
          userId: String(org.ownerID || org.ownerId), // Pass user ID from org
          cookie: cookieString
        }).then(auth => {
          // Initialize web API client after auth succeeds
          if (auth && auth.usingWebApi) {
            webApiClient.setCredentials({
              cookie: cookieString,
              userId: String(org.ownerID || org.ownerId),
              orgId: String(org.id)
            });
            console.log('[Cookie Interceptor] Web API client initialized');
          }
        }).catch(err => {
          console.error('[Cookie Interceptor] Auth processing error:', err);
        });
      }
      
      return data;
    }
  } catch (error) {
    console.log('[Cookie Interceptor] Web app API test error:', error.message);
  }
  
  // Try to find token endpoint that accepts cookies
  try {
    const tokenEndpoints = [
      'https://product.filevineapp.com/api/token',
      'https://product.filevineapp.com/api/auth/token',
      'https://identity.filevine.com/connect/token',
      'https://api.filevineapp.com/token'
    ];
    
    for (const endpoint of tokenEndpoints) {
      try {
        const response = await fetch(endpoint, {
          method: 'POST',
          headers: {
            'Cookie': cookieString,
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          credentials: 'include',
          body: 'grant_type=client_credentials'
        });
        
        if (response.ok) {
          const data = await response.json();
          if (data.access_token) {
            console.log('[Cookie Interceptor] ✅ Found token endpoint!', endpoint);
            return data;
          }
        }
      } catch (e) {
        // Try next endpoint
      }
    }
  } catch (error) {
    console.log('[Cookie Interceptor] Token endpoint search failed:', error.message);
  }
  
  console.log('[Cookie Interceptor] Need to find Bearer token source or use web app API');
  return null;
}
