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

test.describe('Reopen/Reassign Tests', () => {
  test.setTimeout(120000);

  test('reopen closed complaint', 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);
    await api.changeComplaintStatus(complaintId, 'resolved', {
      resolution: 'E2E test - initial resolution',
      resolution_category: 'full_action_taken',
    });
    await api.changeComplaintStatus(complaintId, 'closed');

    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 reopenResp = await sessionPost(page, `/complaints/${complaintId}/reopen/`, {
      note: 'E2E test - reopening complaint for further action',
    });
    expect([200, 302].includes(reopenResp.status())).toBeTruthy();
    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).toMatch(/in_progress|reopened|Reopened/i);
    await page.waitForTimeout(800);
  });

  test('reassign complaint to another user', 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 assignResp = await sessionPost(page, `/complaints/${complaintId}/assign/`, {
      user_id: '8bc6170f-b64b-4946-9e2f-5a9b93006cea',
      note: 'E2E test - reassigning complaint',
    });
    expect([200, 302].includes(assignResp.status())).toBeTruthy();
    await page.waitForTimeout(800);
  });

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

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

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

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

    await api.respondToInquiry(inquiryId, 'E2E test - initial response');

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

    const reopenResp = await sessionPost(page, `/inquiries/${inquiryId}/reopen/`, {
      note: 'E2E test - reopening inquiry',
    });
    expect([200, 302].includes(reopenResp.status())).toBeTruthy();
    await page.waitForTimeout(800);
  });

  test('reopen closed observation', 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 reopen 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: 'assigned',
      note: 'E2E test',
    });
    await page.waitForTimeout(800);

    await sessionPost(page, `/observations/${obsId}/status/`, { status: 'resolved', comment: 'E2E resolved' });
    await page.waitForTimeout(800);

    await sessionPost(page, `/observations/${obsId}/status/`, { status: 'closed', comment: 'E2E closed' });
    await page.waitForTimeout(800);

    const reopenResp = await sessionPost(page, `/observations/${obsId}/reopen/`, {
      comment: 'E2E test - reopening observation',
    });
    expect([200, 302].includes(reopenResp.status())).toBeTruthy();
    await page.waitForTimeout(800);
  });
});
