import { test, expect } from '@playwright/test';
import { RoleAuthHelper, submitContentForm } from '../../helpers/helpers';

const GOV_SOURCE_ID = 'cb92949e-3b11-444d-8f14-51193cb33ad7';

test.describe('Government Ticket Tests', () => {
  test.setTimeout(120000);
  test.describe.configure({ mode: 'serial' });

  let ticketId: string;

  test('create government ticket', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('px_admin');
    await page.waitForTimeout(800);

    await page.goto('/complaints/government-tickets/create/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const pageText = (await page.textContent('body')) || '';
    if (pageText.includes('404') || pageText.includes('403') || pageText.includes("don't have permission")) {
      test.skip();
      return;
    }

    const sourceField = page.locator('select[name="source"], #id_source');
    if (await sourceField.count() > 0) { await sourceField.selectOption(GOV_SOURCE_ID); await page.waitForTimeout(400); }
    const nameField = page.locator('input[name="complainant_name"], #id_complainant_name');
    if (await nameField.count() > 0) { await nameField.fill(`E2E Gov Test ${Date.now()}`); await page.waitForTimeout(400); }
    const contentField = page.locator('textarea[name="content"], #id_content');
    if (await contentField.count() > 0) { await contentField.fill(`E2E government ticket test ${Date.now()}. Please ignore.`); await page.waitForTimeout(400); }
    const dateField = page.locator('input[name="received_date"], #id_received_date');
    if (await dateField.count() > 0) {
      const now = new Date();
      const p = (n: number) => String(n).padStart(2, '0');
      await dateField.fill(`${now.getFullYear()}-${p(now.getMonth()+1)}-${p(now.getDate())}T${p(now.getHours())}:${p(now.getMinutes())}`);
      await page.waitForTimeout(400);
    }

    await submitContentForm(page);

    const url = page.url();
    const m = url.match(/government-tickets\/([0-9a-f-]+)\/?$/);
    ticketId = m ? m[1] : '';
    expect(url).not.toContain('/create/');
    await page.waitForTimeout(800);
  });

  test('close government ticket', async ({ page }) => {
    if (!ticketId) { test.skip(); return; }

    const auth = new RoleAuthHelper(page);
    await auth.login('px_admin');
    await page.waitForTimeout(800);

    await page.goto(`/complaints/government-tickets/${ticketId}/edit/`);
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const statusField = page.locator('select[name="status"], #id_status');
    if (await statusField.count() > 0) {
      await statusField.selectOption('closed');
      await submitContentForm(page);
    }
    expect(page.url()).not.toContain('/create/');
    await page.waitForTimeout(800);
  });

  test('create another government ticket for conversion', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('px_admin');
    await page.waitForTimeout(800);

    await page.goto('/complaints/government-tickets/create/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const sourceField = page.locator('select[name="source"], #id_source');
    if (await sourceField.count() > 0) { await sourceField.selectOption(GOV_SOURCE_ID); await page.waitForTimeout(400); }
    const nameField = page.locator('input[name="complainant_name"], #id_complainant_name');
    if (await nameField.count() > 0) { await nameField.fill(`E2E Gov Test 2 ${Date.now()}`); await page.waitForTimeout(400); }
    const contentField = page.locator('textarea[name="content"], #id_content');
    if (await contentField.count() > 0) { await contentField.fill(`E2E second government ticket test ${Date.now()}. To be converted.`); await page.waitForTimeout(400); }
    const dateField = page.locator('input[name="received_date"], #id_received_date');
    if (await dateField.count() > 0) {
      const now = new Date();
      const p = (n: number) => String(n).padStart(2, '0');
      await dateField.fill(`${now.getFullYear()}-${p(now.getMonth()+1)}-${p(now.getDate())}T${p(now.getHours())}:${p(now.getMinutes())}`);
      await page.waitForTimeout(400);
    }

    await submitContentForm(page);

    const url = page.url();
    const m = url.match(/government-tickets\/([0-9a-f-]+)\/?$/);
    ticketId = m ? m[1] : ticketId;
    expect(url).not.toContain('/create/');
    await page.waitForTimeout(800);
  });

  test('convert government ticket to complaint', async ({ page }) => {
    if (!ticketId) { test.skip(); return; }

    const auth = new RoleAuthHelper(page);
    await auth.login('px_admin');
    await page.waitForTimeout(800);

    await page.goto(`/complaints/government-tickets/${ticketId}/convert/`);
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(3000);

    const url = page.url();
    const ok = url.includes('/complaints/') && !url.includes('government-tickets');
    expect(ok).toBeTruthy();
    await page.waitForTimeout(800);
  });
});
