import { test, expect } from '@playwright/test';
import { adminPath, apiPost, ensureDataSource, ensureMailshot, cleanupByNames } from './helpers.mjs';

test('run/test pages: load and failure-path API assertions', async ({ page, request }) => {
  const uniq = `${Date.now()}_${Math.floor(Math.random() * 100000)}`;
  const dsName = `e2e_run_ds_${uniq}`;
  const purpose = `e2e_run_ms_${uniq}`;

  try {
    await ensureDataSource(request, dsName, 'contacts');
    const saved = await ensureMailshot(request, {
      Purpose: purpose,
      DataSource: dsName,
      CC: '',
      BCC: '',
      Subject: 'Subj {{ contacts_id }}',
      Message: '<p>Hi {{ contacts_id }}</p>',
      PDFAttachment: '<p>PDF</p>',
      AttachmentNames: '[]',
      PDFFilenameDerivedFrom: '',
      RecipientEmailField: 'contacts.contact_email_1',
      ReplyTo: ''
    });

    await page.goto(`${adminPath('feca-mailshots-run')}&mailshot_id=${encodeURIComponent(String(saved.id || ''))}`);
    await expect(page.getByRole('heading', { name: 'Run Mailshot' })).toBeVisible();
    await expect(page.getByText('Recipient rows:')).toBeVisible();
    await expect(page.getByRole('button', { name: 'Load' })).toHaveCount(0);

    await page.goto(adminPath('feca-mailshots-test'));
    await expect(page.getByRole('heading', { name: 'Mailshot Test' })).toBeVisible();

    const renderTest = await apiPost(request, 'feca_mailshots_test_api', 'render_test', {
      mailshot_id: String(saved.id || ''),
      recipient_index: '0'
    });
    expect(renderTest.ok).toBeTruthy();
    expect(String(renderTest?.rendered?.subject || '')).toContain('Subj');

    const runInvalid = await apiPost(request, 'feca_mailshots_run_api', 'run_mailshot', { mailshot_id: '0' });
    expect(runInvalid.ok).toBeFalsy();
    const runInvalidMessage = String((runInvalid.errors || []).join(' | ') || runInvalid.error || '');
    // Current behavior returns "Mailshot not found." for id=0 before credential checks.
    expect(runInvalidMessage).toContain('Mailshot not found');

    const sendBlank = await apiPost(request, 'feca_mailshots_test_api', 'send_test', {
      mailshot_id: '1',
      recipient_index: '0',
      test_email: ''
    });
    expect(sendBlank.ok).toBeFalsy();
    expect(String((sendBlank.errors || []).join(' | ') || sendBlank.error || '')).toContain('Test email address is required');
  } finally {
    try {
      await cleanupByNames(request, { dataSourceNames: [dsName], mailshotPurposes: [purpose] });
    } catch {
      // best effort
    }
  }
});

test('mailshot test page renders complex PDF preview through UI postback', async ({ page, request }) => {
  const uniq = `${Date.now()}_${Math.floor(Math.random() * 100000)}`;
  const dsName = `e2e_render_ui_ds_${uniq}`;
  const purpose = `e2e_render_ui_ms_${uniq}`;
  const repeatedRows = Array.from({ length: 180 }, (_, i) => (
    `<tr><td>${i + 1}</td><td>{{ contacts_id }}</td><td>PDF_RENDER_MARKER_${i}</td></tr>`
  )).join('');
  const pdfHtml = `<html><body><h1>PDF_RENDER_MARKER</h1><table>${repeatedRows}</table></body></html>`;

  try {
    await ensureDataSource(request, dsName, 'contacts');
    await ensureMailshot(request, {
      Purpose: purpose,
      DataSource: dsName,
      CC: '',
      BCC: '',
      Subject: 'UI render {{ contacts_id }}',
      Message: '<p>Message {{ contacts_id }}</p>',
      PDFAttachment: pdfHtml,
      AttachmentNames: '[]',
      PDFFilenameDerivedFrom: '',
      RecipientEmailField: 'contacts.contact_email_1',
      ReplyTo: ''
    });

    await page.goto(adminPath('feca-mailshots-test'));
    await page.locator('#mst_mailshot_id').selectOption({ label: purpose });
    await page.waitForURL(/mailshot_id=/);

    await page.getByRole('button', { name: 'Render Test (No Send)' }).click();
    await expect(page.locator('.feca-banner-success')).toContainText('Test action succeeded.');
    await expect(page.locator('#ms-render-preview-modal')).toBeVisible();
    await expect(page.frameLocator('#ms-render-pdf-frame').locator('body')).toContainText('PDF_RENDER_MARKER');
  } finally {
    try {
      await cleanupByNames(request, { dataSourceNames: [dsName], mailshotPurposes: [purpose] });
    } catch {
      // best effort
    }
  }
});
