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

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

  test('track complaint status changes', async ({ page }) => {
    const api = new ApiHelper(page);
    await api.authenticate('px_admin');
    const { body: cb } = await api.createComplaint();
    const complaintId = cb?.id;
    const ref = cb?.reference_number || '';
    if (!complaintId) { test.skip(); return; }

    await api.activateComplaint(complaintId);
    await api.changeComplaintStatus(complaintId, 'resolved', {
      resolution: 'E2E test - resolved',
      resolution_category: 'full_action_taken',
    });

    await page.goto('/complaints/public/track/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2500);

    const refInput = page.locator('input[name="reference_number"]');
    if (await refInput.count() > 0 && ref) {
      await refInput.fill(ref);
      await page.waitForTimeout(600);
      await page.click('button[type="submit"]');
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(3000);

      const pageText = (await page.textContent('body')) || '';
      expect(pageText).toContain(ref);
      expect(pageText).toMatch(/resolved|Resolved/i);
    }
    await page.waitForTimeout(800);
  });

  test('track inquiry status via unified page', async ({ page }) => {
    const api = new ApiHelper(page);
    await api.authenticate('px_admin');
    const { body: ib } = await api.createInquiry();
    const inquiryId = ib?.id;
    const ref = ib?.reference_number || '';
    if (!inquiryId || !ref) { test.skip(); return; }

    await api.respondToInquiry(inquiryId, 'E2E test - inquiry resolved');

    const trackResp = await page.request.get(`/core/api/track/?type=inquiry&reference=${encodeURIComponent(ref)}`);
    expect(trackResp.status()).toBe(200);
    const trackBody = await trackResp.json().catch(() => null);
    if (trackBody) {
      expect(trackBody.found || trackBody.status || trackBody.reference).toBeTruthy();
    }
    await page.waitForTimeout(800);
  });

  test('track observation status changes', async ({ page }) => {
    const api = new ApiHelper(page);
    await api.authenticate('px_admin');

    const obsResp = await page.request.post('/core/public/observation/submit/', {
      data: {
        description: `E2E track obs ${Date.now()}`,
        hospital: '7e4d08ce-2e0a-4184-8297-7acd418184a6',
      },
      headers: { 'Content-Type': 'application/json' },
    });
    const obsBody = await obsResp.json().catch(() => null);
    const trackingCode = obsBody?.tracking_code || '';
    const obsId = obsBody?.id || '';

    if (!trackingCode) { test.skip(); return; }

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

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

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

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

    const codeInput = page.locator('input[name="tracking_code"]');
    if (await codeInput.count() > 0) {
      await codeInput.fill(trackingCode);
      await page.waitForTimeout(600);
      await page.click('button[type="submit"]');
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(3000);

      const pageText = (await page.textContent('body')) || '';
      expect(pageText).toContain(trackingCode);
    }
    await page.waitForTimeout(800);
  });
});
