// @ts-nocheck
declare var Promise: any;
declare var globalThis: any;
/**
 * E2E Tests: Procesos / Install Twig Validation
 *
 * Valida que:
 * - Template renderiza correctamente
 * - Checkboxes tienen validación frontend
 * - AJAX calls funcionan con respuestas esperadas
 * - Form submission maneja errores correctamente
 */

import { test, expect } from '../fixtures/fixtures';
import { ROUTES } from '../fixtures/data';

test.describe('Procesos - Install Template', () => {
  test.beforeEach(async ({ page, appPage }) => {
    const adminUser = process.env.E2E_ADMIN_USER || 'admin';
    const adminPassword = process.env.E2E_ADMIN_PASSWORD || '';

    test.skip(!adminPassword, 'Definir E2E_ADMIN_PASSWORD para ejecutar pruebas protegidas');

    await appPage.login(adminUser, adminPassword);

    // Solo navegar si no estamos ya en la ruta correcta (evita re-navegacion innecesaria)
    if (!page.url().includes('procesos/install')) {
      await appPage.goto(ROUTES.install);
    }
  });

  test('Página carga correctamente', async ({ page }) => {
    // Validar que página devuelve 200
    const response = await page.goto(ROUTES.install, { waitUntil: 'commit' });
    const statusCode = response ? response.status() : 0;
    expect(statusCode).toBe(200);

    // Validar que contiene elementos clave del template
    await expect(
      page.getByRole('heading', { name: /¿Desea Actualizar los cambios en la Base de Datos\?/i })
    ).toBeVisible();
    await expect(page.locator('a#generar')).toBeVisible();
  });

  test('Checkboxes existen con valores por defecto', async ({ page }) => {
    // Validar checkboxes
    const checkboxes = [
      { id: 'readOnly', expected: true },
      { id: 'crearTriggers', expected: true },
      { id: 'crearVistas', expected: true },
      { id: 'revisarMayusculas', expected: true },
      { id: 'revisarPLUs', expected: true },
      { id: 'borrar', expected: false },
    ];

    for (const checkbox of checkboxes) {
      const isChecked = await page.isChecked(`#${checkbox.id}`);
      expect(isChecked).toBe(checkbox.expected);
    }
  });

  test('Validación de cierres HTML: h3 bien formados', async ({ page }) => {
    // Validar que los encabezados están bien cerrados
    await page.goto(ROUTES.install, { waitUntil: 'commit' });
    const html = await page.content();

    // Verificar que no hay cierres directos mal formados: <h3>texto</h2>
    expect(html).not.toMatch(/<h3\b[^>]*>[^<]*<\/h2>/i);

    // Verificar que existen h3 correctamente cerrados
    expect(html).toMatch(/<h3[^>]*>SERVER_ID:.*?<\/h3>/s);
  });

  test('Mensaje de progreso modal existe', async ({ page }) => {
    const modal = page.locator('#myModal');
    expect(await modal.count()).toBeGreaterThan(0);
  });

  test('Alert helper (bootbox) accesible', async ({ page }) => {
    // Esperar a que los scripts JS terminen de cargar
    await page.waitForFunction(() => globalThis.bootbox !== undefined, null, {
      timeout: 30000,
    }).catch(() => null);

    const bootstrapLoaded = await page.evaluate(() => globalThis.bootbox !== undefined);
    expect(bootstrapLoaded).toBe(true);
  });

  test('Función ejecutarSqlInstalacion existe', async ({ page }) => {
    // Esperar a que los scripts JS terminen de cargar
    await page.waitForFunction(() => typeof globalThis.ejecutarSqlInstalacion === 'function', null, {
      timeout: 30000,
    }).catch(() => null);

    const funcExists = await page.evaluate(() => typeof globalThis.ejecutarSqlInstalacion === 'function');
    expect(funcExists).toBe(true);
  });

  test('Form values sanitized on submit', async ({ page }) => {
    // Validar que los valores de checkbox se pueden cambiar
    const initialState = await page.isChecked('#readOnly');

    if (initialState) {
      await page.uncheck('#readOnly');
      expect(await page.isChecked('#readOnly')).toBe(false);
    } else {
      await page.check('#readOnly');
      expect(await page.isChecked('#readOnly')).toBe(true);
    }
  });

  test('AJAX error handling muestra bootbox alert', async ({ page }) => {
    // Validar que AJAX errors disparan bootbox.alert
    const alertSpy = page.evaluate(() => {
      const bootbox = globalThis.bootbox;
      return !!bootbox && bootbox.alert !== undefined;
    });

    expect(await alertSpy).toBe(true);
  });
});
