/**
 * Yahoo Finance Crumb Helper
 * Fetches and caches the A3 cookie and crumb needed for v10/v11 API endpoints
 */

let crumb = null;
let cookie = null;
let crumbPromise = null;

const DEFAULT_HEADERS = {
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  'Accept': '*/*',
  'Accept-Language': 'en-US,en;q=0.9',
};

async function fetchCrumbAndCookie() {
  try {
    // 1. Get Cookie
    const response = await fetch('https://fc.yahoo.com', {
      headers: DEFAULT_HEADERS,
      redirect: 'manual' // We only need the headers
    });
    
    const setCookieHeader = response.headers.get('set-cookie');
    if (!setCookieHeader) {
      throw new Error('No set-cookie header received from fc.yahoo.com');
    }
    
    // Extract A3 cookie
    const match = setCookieHeader.match(/(A3=[^;]+)/);
    if (!match) {
      throw new Error('A3 cookie not found in set-cookie header');
    }
    cookie = match[1];

    // 2. Get Crumb
    const crumbRes = await fetch('https://query1.finance.yahoo.com/v1/test/getcrumb', {
      headers: {
        ...DEFAULT_HEADERS,
        'Cookie': cookie,
      }
    });

    if (!crumbRes.ok) {
      throw new Error(`Failed to get crumb, status: ${crumbRes.status}`);
    }

    crumb = await crumbRes.text();
    return { cookie, crumb };
  } catch (err) {
    console.error('[YahooCrumb] Error fetching crumb:', err.message);
    cookie = null;
    crumb = null;
    throw err;
  }
}

export async function getYahooAuth() {
  if (cookie && crumb) {
    return { cookie, crumb };
  }
  
  if (!crumbPromise) {
    crumbPromise = fetchCrumbAndCookie().finally(() => {
      crumbPromise = null;
    });
  }
  
  return crumbPromise;
}

export async function yfFetchAuth(url) {
  const { cookie: currentCookie, crumb: currentCrumb } = await getYahooAuth();
  
  const separator = url.includes('?') ? '&' : '?';
  const urlWithCrumb = `${url}${separator}crumb=${currentCrumb}`;
  
  const res = await fetch(urlWithCrumb, {
    headers: {
      ...DEFAULT_HEADERS,
      'Cookie': currentCookie,
    }
  });

  if (!res.ok) {
    // If auth fails, we might need a new crumb
    if (res.status === 401 || res.status === 403) {
      crumb = null;
      cookie = null;
      throw new Error(`Auth failed (${res.status}), crumb invalidated`);
    }
    throw new Error(`Yahoo Finance HTTP ${res.status} for ${urlWithCrumb}`);
  }

  return res.json();
}
