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

test.describe('Send to Department Across All Entities Tests', () => {
  test.setTimeout(120000);

  test('send complaint to dept, champion responds', async ({ page }) => {
    const api = new ApiHelper(page);
    await api.authenticate('px_admin');
    const { body: cb } = await api.createComplaint();
    const complaintId = cb?.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(`/complaints/${complaintId}/`);
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const sendResp = await sessionPost(page, `/complaints/${complaintId}/send-to/`, {
      recipient_type: 'department',
      department_id: DEPT_ID,
      note: 'E2E test - send complaint to department',
    });
    expect([200, 302].includes(sendResp.status())).toBeTruthy();
    await page.waitForTimeout(800);

    await auth.logout();
    await auth.login('champion');
    await page.waitForTimeout(800);

    await page.goto(`/complaints/${complaintId}/`);
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const pageText = (await page.textContent('body')) || '';
    expect(pageText.length).toBeGreaterThan(0);
    await page.waitForTimeout(800);
  });

  test('send inquiry to dept, champion responds', async ({ page }) => {
    const api = new ApiHelper(page);
    await api.authenticate('px_admin');
    const { body: ib } = await api.createInquiry({ is_outgoing: true, is_straightforward: false });
    const inquiryId = ib?.id;
    if (!inquiryId) { test.skip(); return; }

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

    await sessionPost(page, `/inquiries/${inquiryId}/activate/`, {});
    await page.waitForTimeout(800);

    const transferResp = await sessionPost(page, `/inquiries/${inquiryId}/transfer-to-department/`, {
      department_id: DEPT_ID,
      note_en: 'E2E test - transfer inquiry to department',
      recipient_type: 'staff',
    });
    expect([200, 302].includes(transferResp.status())).toBeTruthy();
    await page.waitForTimeout(800);

    await auth.logout();
    await auth.login('champion');
    await page.waitForTimeout(800);

    const deptResp = await sessionPost(page, `/inquiries/${inquiryId}/department-response/`, {
      response_en: 'E2E test - champion response to inquiry',
    });
    expect([200, 302].includes(deptResp.status())).toBeTruthy();
    await page.waitForTimeout(800);
  });

  test('send observation to dept, champion responds', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');
    await page.waitForTimeout(800);

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

    await page.fill('textarea[name="description"]', `E2E dept obs ${Date.now()}. Please ignore.`);
    const dt = page.locator('input[name="incident_datetime"]');
    if (await dt.count() > 0) {
      const now = new Date();
      const p = (n: number) => String(n).padStart(2, '0');
      await dt.fill(`${now.getFullYear()}-${p(now.getMonth()+1)}-${p(now.getDate())}T${p(now.getHours())}:${p(now.getMinutes())}`);
    }
    await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
    await page.waitForTimeout(1200);
    await page.evaluate(() => {
      const f = document.getElementById('observationForm') as HTMLFormElement;
      if (f) f.submit();
    });
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(3000);

    const url = page.url();
    const m = url.match(/\/observations\/([0-9a-f-]+)\/?$/);
    const obsId = m ? m[1] : '';
    if (!obsId) { test.skip(); return; }

    await sessionPost(page, `/observations/${obsId}/triage/`, {
      status: 'triaged',
      assigned_department: DEPT_ID,
      note: 'E2E triage',
    });
    await page.waitForTimeout(800);

    const sendResp = await sessionPost(page, `/observations/${obsId}/send-to-department/`, {
      department_id: DEPT_ID,
      note_en: 'E2E test - send observation to department',
      recipient_type: 'staff',
    });
    expect([200, 302].includes(sendResp.status())).toBeTruthy();
    await page.waitForTimeout(800);

    await auth.logout();
    await auth.login('champion');
    await page.waitForTimeout(800);

    await page.goto(`/observations/${obsId}/`);
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const deptResp = await sessionPost(page, `/observations/${obsId}/department-response/`, {
      response_en: 'E2E test - champion response to observation',
    });
    expect([200, 302].includes(deptResp.status())).toBeTruthy();
    await page.waitForTimeout(800);
  });
});
