import { test, expect } from '@playwright/test';
import { RoleAuthHelper, submitContentForm } from '../../helpers/helpers';
import { ApiHelper, HOSPITAL_ID } from '../../helpers/api-helper';

test.describe('RCA Tests', () => {
  test.setTimeout(120000);

  test('create standalone RCA', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');
    await page.waitForTimeout(800);

    await page.goto('/rca/create/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const titleField = page.locator('input[name="title"], #id_title');
    if (await titleField.count() > 0) { await titleField.fill(`E2E Standalone RCA ${Date.now()}`); await page.waitForTimeout(400); }
    const descField = page.locator('textarea[name="description"], #id_description');
    if (await descField.count() > 0) { await descField.fill(`E2E standalone RCA test ${Date.now()}. Please ignore.`); await page.waitForTimeout(400); }
    const hospField = page.locator('select[name="hospital"], #id_hospital');
    if (await hospField.count() > 0) {
      const val = await hospField.inputValue();
      if (!val) { await hospField.selectOption(HOSPITAL_ID); await page.waitForTimeout(400); }
    }

    await submitContentForm(page);

    const url = page.url();
    const ok = url.match(/\/rca\/[0-9a-f-]+\/?$/) || !url.includes('/create/');
    expect(ok).toBeTruthy();
    await page.waitForTimeout(800);
  });

  test('create RCA from complaint', async ({ page }) => {
    const api = new ApiHelper(page);
    await api.authenticate('px_admin');
    const { body } = await api.createComplaint();
    const complaintId = body?.id;
    if (!complaintId) { test.skip(); return; }
    await api.activateComplaint(complaintId);

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

    await page.goto(`/rca/create/?related_model=complaint&related_id=${complaintId}`);
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

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

    const titleField = page.locator('input[name="title"], #id_title');
    if (await titleField.count() > 0) {
      const existingTitle = await titleField.inputValue();
      if (!existingTitle) await titleField.fill(`E2E RCA from Complaint ${Date.now()}`);
    }
    const descField = page.locator('textarea[name="description"], #id_description');
    if (await descField.count() > 0) {
      const existingDesc = await descField.inputValue();
      if (!existingDesc) await descField.fill(`E2E RCA from complaint ${Date.now()}. Please ignore.`);
    }

    await submitContentForm(page);

    const url = page.url();
    const ok = url.match(/\/rca\/[0-9a-f-]+\/?$/) || !url.includes('/create/');
    expect(ok).toBeTruthy();
    await page.waitForTimeout(800);
  });

  test('create RCA from observation', async ({ page }) => {
    const api = new ApiHelper(page);
    await api.authenticate('px_admin');

    await page.goto('/core/public/submit/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(1000);
    const csrfCookie = await page.context().cookies();
    const csrf = csrfCookie.find(c => c.name === 'csrftoken')?.value || '';
    const obsResp = await page.request.post('/core/public/observation/submit/', {
      form: { description: `E2E RCA obs ${Date.now()}`, hospital: HOSPITAL_ID, severity: 'low', csrfmiddlewaretoken: csrf },
      headers: csrf ? { 'X-CSRFToken': csrf, Referer: 'http://localhost:8000/' } : {},
    });
    const obsBody = await obsResp.json().catch(() => null);
    const obsId = obsBody?.observation_id || obsBody?.id || '';
    if (!obsId) { test.skip(); return; }

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

    await page.goto(`/rca/create/?related_model=observation&related_id=${obsId}`);
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

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

    const titleField = page.locator('input[name="title"], #id_title');
    if (await titleField.count() > 0) {
      const existingTitle = await titleField.inputValue();
      if (!existingTitle) await titleField.fill(`E2E RCA from Observation ${Date.now()}`);
    }
    const descField = page.locator('textarea[name="description"], #id_description');
    if (await descField.count() > 0) {
      const existingDesc = await descField.inputValue();
      if (!existingDesc) await descField.fill(`E2E RCA from observation ${Date.now()}. Please ignore.`);
    }

    await submitContentForm(page);

    const url = page.url();
    const ok = url.match(/\/rca\/[0-9a-f-]+\/?$/) || !url.includes('/create/');
    expect(ok).toBeTruthy();
    await page.waitForTimeout(800);
  });

  test('create RCA from inquiry', async ({ page }) => {
    const api = new ApiHelper(page);
    await api.authenticate('px_admin');
    const { body } = await api.createInquiry();
    const inquiryId = body?.id;
    if (!inquiryId) { test.skip(); return; }

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

    await page.goto(`/rca/create/?related_model=inquiry&related_id=${inquiryId}`);
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

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

    const titleField = page.locator('input[name="title"], #id_title');
    if (await titleField.count() > 0) {
      const existingTitle = await titleField.inputValue();
      expect(existingTitle.length).toBeGreaterThan(0);
    }
    await page.waitForTimeout(800);
  });
});
