import { type Page } from 'playwright';

const TIMEOUT = 60_000;

export async function loginToSatOpinion(
  page: Page,
  cerPath: string,
  keyPath: string,
  password: string,
): Promise<Page> {
  // Step 1: Navigate to SAT public page
  const publicUrl = 'https://www.sat.gob.mx/portal/public/tramites/opinion-del-cumplimiento';
  console.log('[SAT Opinion] Navigating to SAT public page...');
  await page.goto(publicUrl, { waitUntil: 'domcontentloaded', timeout: TIMEOUT });
  await page.waitForTimeout(2000);

  // Step 2: Click "Obtén la Opinión del cumplimiento" tab
  console.log('[SAT Opinion] Clicking "Obtén la Opinión del cumplimiento"...');
  const obtenerOpcion = page.locator('text=Obt').first();
  await obtenerOpcion.waitFor({ state: 'visible', timeout: TIMEOUT });
  await obtenerOpcion.click();
  await page.waitForTimeout(2000);

  // Step 3: Expand "De tu empresa" accordion
  console.log('[SAT Opinion] Expanding "De tu empresa" section...');
  const empresaOption = page.locator('text=De tu empresa').first();
  await empresaOption.waitFor({ state: 'visible', timeout: TIMEOUT });
  await empresaOption.click();
  await page.waitForTimeout(2000);

  // Step 4: Click "Ingresa" link — opens new tab (target=_blank)
  console.log('[SAT Opinion] Clicking "Ingresa" (opens new tab)...');
  const ingresaLink = page.locator('a:has-text("Ingresa")').first();
  await ingresaLink.waitFor({ state: 'visible', timeout: TIMEOUT });

  const [loginPage] = await Promise.all([
    page.context().waitForEvent('page', { timeout: TIMEOUT }),
    ingresaLink.click(),
  ]);
  await loginPage.waitForLoadState('domcontentloaded', { timeout: TIMEOUT });
  await loginPage.waitForTimeout(2000);

  // Step 5: Switch to e.firma login
  console.log('[SAT Opinion] Clicking e.firma button...');
  const efirmaButton = loginPage.locator('button:has-text("e.firma"), input[value*="firma"], a:has-text("e.firma")').first();
  await efirmaButton.waitFor({ state: 'visible', timeout: TIMEOUT });
  await efirmaButton.click();
  await loginPage.waitForLoadState('domcontentloaded', { timeout: TIMEOUT });
  await loginPage.waitForTimeout(2000);

  // Step 6: Upload .cer
  console.log('[SAT Opinion] Uploading .cer...');
  const cerInput = loginPage.locator('input[type="file"]').first();
  await cerInput.waitFor({ state: 'attached', timeout: TIMEOUT });
  await cerInput.setInputFiles(cerPath);
  await loginPage.waitForTimeout(500);

  // Step 7: Upload .key
  console.log('[SAT Opinion] Uploading .key...');
  const keyInput = loginPage.locator('input[type="file"]').nth(1);
  await keyInput.waitFor({ state: 'attached', timeout: TIMEOUT });
  await keyInput.setInputFiles(keyPath);
  await loginPage.waitForTimeout(500);

  // Step 8: Enter password
  console.log('[SAT Opinion] Entering password...');
  const passwordInput = loginPage.locator('input[type="password"]').first();
  await passwordInput.waitFor({ state: 'visible', timeout: TIMEOUT });
  await passwordInput.fill(password);

  // Step 9: Submit
  console.log('[SAT Opinion] Submitting login...');
  const submitButton = loginPage.locator('button:has-text("Enviar"), input[value="Enviar"], a:has-text("Enviar"), input[type="submit"], button[type="submit"]').first();
  await submitButton.waitFor({ state: 'visible', timeout: TIMEOUT });
  await submitButton.click();

  // Step 10: Wait for auth + redirect to report
  console.log('[SAT Opinion] Waiting for authentication...');
  await loginPage.waitForTimeout(8000);

  const currentUrl = loginPage.url();
  if (!currentUrl.includes('reporteOpinion32DContribuyente')) {
    const baseUrl = currentUrl.replace(/#.*$/, '').replace(/\?.*$/, '');
    const reporteUrl = baseUrl + '#/reporteOpinion32DContribuyente';
    console.log(`[SAT Opinion] Navigating to report: ${reporteUrl}`);
    await loginPage.goto(reporteUrl, { waitUntil: 'domcontentloaded', timeout: TIMEOUT });
    await loginPage.waitForTimeout(5000);
  }

  console.log('[SAT Opinion] Login completed.');
  return loginPage;
}
