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

test.describe('Inquiry Scenario Tests', () => {

  test.describe('Scenario A: Raised to Department (Outgoing)', () => {
    test.describe.configure({ mode: 'serial' });

    let inquiryId: string;

    test('create outgoing inquiry and activate', async ({ page }) => {
      const api = new ApiHelper(page);
      await api.authenticate('px_admin');

      const { response, body } = await api.createInquiry({
        subject: `E2E Dept Inquiry ${Date.now()}`,
        message: 'E2E scenario test - raised to department flow. Please ignore.',
        is_straightforward: false,
        is_outgoing: true,
      });
      expect(response.status()).toBe(201);
      inquiryId = body.id;

      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);

      const activateResp = await sessionPost(page, `/inquiries/${inquiryId}/activate/`, {});
      if (![200, 302].includes(activateResp.status())) {
        console.log(`Activate failed with status: ${activateResp.status}, ok: ${activateResp.ok}`);
        const bodyText = await page.textContent('body');
        console.log(`Page snippet: ${bodyText?.substring(0, 300)}`);
      }
      expect([200, 302].includes(activateResp.status())).toBeTruthy();
      await page.waitForTimeout(800);

      await page.reload();
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(1500);
    });

    test('transfer to department', async ({ page }) => {
      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);

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

      await page.reload();
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(1500);
    });

    test('submit department response and review', async ({ page }) => {
      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);

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

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

      const reviewResp = await sessionPost(page, `/inquiries/${inquiryId}/review-dept-response/`, {
        acceptance_status: 'acceptable',
        acceptance_notes: 'E2E test - department response is acceptable',
      });
      expect([200, 302].includes(reviewResp.status())).toBeTruthy();
      await page.waitForTimeout(800);

      await page.reload();
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(1500);
    });

    test('respond to inquiry and verify resolution', async ({ page }) => {
      const api = new ApiHelper(page);
      await api.authenticate('px_admin');

      const respondResp = await api.respondToInquiry(
        inquiryId,
        'E2E test - inquiry resolved based on department response. Thank you for your patience.'
      );
      expect([200, 201, 204].includes(respondResp.status())).toBeTruthy();

      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);

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

    test('verify transfer count and department info in detail', async ({ page }) => {
      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);

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

  test.describe('Scenario B: Handled Immediately (Straightforward)', () => {
    test.describe.configure({ mode: 'serial' });

    let inquiryId: string;

    test('create straightforward inquiry and resolve directly', async ({ page }) => {
      const api = new ApiHelper(page);
      await api.authenticate('px_admin');

      const { response, body } = await api.createInquiry({
        subject: `E2E Direct Inquiry ${Date.now()}`,
        message: 'E2E scenario test - handled immediately. Please ignore.',
        is_straightforward: true,
      });
      expect(response.status()).toBe(201);
      inquiryId = body.id;

      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);

      const respondResp = await api.respondToInquiry(
        inquiryId,
        'E2E test - direct response provided, no department coordination needed.'
      );
      expect([200, 201, 204].includes(respondResp.status())).toBeTruthy();

      await page.reload();
      await page.waitForLoadState('domcontentloaded');
      await page.waitForTimeout(1500);
    });

    test('verify resolved status in admin UI', async ({ page }) => {
      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);

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

    test('verify no department transfer shown', async ({ page }) => {
      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);

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

  test.describe('Scenario C: Let Expire (SLA Breach)', () => {
    test.describe.configure({ mode: 'serial' });

    let inquiryId: string;

    test('create inquiry, activate and backdate SLA', async ({ page }) => {
      const api = new ApiHelper(page);
      await api.authenticate('px_admin');

      const { response, body } = await api.createInquiry({
        subject: `E2E Expire Inquiry ${Date.now()}`,
        message: 'E2E scenario test - SLA expiry flow. Please ignore.',
      });
      expect(response.status()).toBe(201);
      inquiryId = body.id;

      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);

      const patchResp = await api.setDueAtPast('inquiries', inquiryId, 7);
      expect([200, 204].includes(patchResp.status())).toBeTruthy();
    });

    test('verify overdue indicator in inquiry list', async ({ page }) => {
      const auth = new RoleAuthHelper(page);
      await auth.login('hospital_admin');
      await page.waitForTimeout(800);

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

      const tableText = await page.locator('table').textContent();
      expect(tableText).toBeTruthy();
      await page.waitForTimeout(800);
    });

    test('verify overdue indicator in inquiry detail', async ({ page }) => {
      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);

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

    test('inquiry can still be responded to after SLA breach', async ({ page }) => {
      const api = new ApiHelper(page);
      await api.authenticate('px_admin');

      const respondResp = await api.respondToInquiry(
        inquiryId,
        'E2E test - response provided after SLA breach'
      );
      expect([200, 201, 204].includes(respondResp.status())).toBeTruthy();
    });
  });
});
