import puppeteer from 'puppeteer';

export interface HttpData {
  status: number;
  headers: Record<string, string>;
  lastChecked: Date;
}

export const fetchRenderedPageWithPuppeteer = async (
  url: string
): Promise<{ html: string; httpData: HttpData }> => {
  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();

  await page.setExtraHTTPHeaders({
    Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
  });

  await page.setUserAgent(
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
  );

  const response = await page.goto(url, {
    waitUntil: 'domcontentloaded',
    timeout: 30000,
  });

  

  if (!response) throw new Error('Failed to load page');

  const html = await page.content();

  const httpData: HttpData = {
    status: response.status(),
    headers: response.headers(),
    lastChecked: new Date(),
  };

  await browser.close();

  return { html, httpData };
};
