import { test, expect } from '@playwright/test';
import { adminPath, apiList } from './helpers.mjs';

const runEnabled = process.env.E2E_RENEWAL_ENABLE === '1';
const mailshotPurpose = process.env.E2E_RENEWAL_MAILSHOT_PURPOSE || 'Renewals (pending accounts and contacts)';
const dsName = process.env.E2E_RENEWAL_DATASOURCE || 'renewal_accounts_with_contacts';

test.describe('download pdf ui feedback', () => {
  test.skip(!runEnabled, 'Enable with E2E_RENEWAL_ENABLE=1');

  test('download page has no js syntax errors and shows progress state on submit', async ({ page, request }) => {
    const jsErrors = [];
    page.on('pageerror', (err) => {
      jsErrors.push(String(err && err.message ? err.message : err));
    });

    const mailshotList = await apiList(request, 'feca_mailshots_mailshots_api');
    expect(mailshotList.ok).toBeTruthy();
    const items = Array.isArray(mailshotList.items) ? mailshotList.items : [];
    const existingByPurpose = items.find(
      (row) => String(row.Purpose || '') === mailshotPurpose
    );
    const existingByDataSource = items.find(
      (row) => String(row.DataSource || '') === dsName
    );
    const existing = existingByPurpose || existingByDataSource || items[0];
    expect(existing, 'No mailshots available for Download PDF UI test').toBeTruthy();
    const mailshotId = String((existing && existing.id) || '');
    expect(mailshotId).not.toBe('');

    await page.goto(`${adminPath('feca-mailshots-download-pdf')}&mailshot_id=${encodeURIComponent(mailshotId)}`);
    await expect(page.getByRole('heading', { name: 'Download PDF' })).toBeVisible();
    await page.waitForTimeout(250);
    expect(jsErrors, `Page JS errors: ${jsErrors.join(' | ')}`).toEqual([]);

    await page.evaluate(() => {
      const form = document.getElementById('feca-download-pdf-form');
      if (!form) {
        throw new Error('Download form not found.');
      }
      form.addEventListener('submit', (ev) => {
        ev.preventDefault();
      });
    });

    page.once('dialog', async (dialog) => {
      await dialog.accept();
    });
    await page.getByRole('button', { name: 'Download Merged PDF' }).click();

    await expect(page.locator('#feca-download-progress')).toBeVisible();
    await expect(page.locator('#feca-download-merged-btn')).toBeDisabled();
    await expect(page.locator('#feca-download-zip-btn')).toBeDisabled();
  });
});
