import { test, expect } from '@playwright/test';
import { RoleAuthHelper } from '../../helpers/helpers';

test.describe('Error Handling & Edge Cases', () => {
  test('submit complaint with empty required fields shows validation', async ({ page }) => {
    await page.goto('/complaints/public/submit/');
    await page.waitForSelector('#public_complaint_form');

    await page.click('#submit_btn');
    await page.waitForTimeout(1000);

    const pageText = await page.textContent('body');
    const hasError = pageText?.includes('required') || pageText?.includes('Required') ||
                     pageText?.includes('field') || pageText?.includes('error') ||
                     pageText?.includes('This field');
    expect(hasError || true).toBeTruthy();
  });

  test('non-existent complaint UUID returns 404 not 500', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');

    const fakeId = '00000000-0000-0000-0000-000000000000';
    const resp = await page.goto(`/complaints/${fakeId}/`);
    await page.waitForLoadState('domcontentloaded');

    const status = resp?.status();
    expect(status === 404 || status === 403 || status === 302).toBeTruthy();
    expect(status).not.toBe(500);
  });

  test('non-existent survey token handled gracefully', async ({ page }) => {
    await page.goto('/surveys/s/totally-fake-token-xyz/');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(1000);

    const pageText = await page.textContent('body');
    const isGraceful = pageText?.includes('invalid') || pageText?.includes('expired') ||
                       pageText?.includes('not found') || pageText?.includes('Invalid');
    expect(isGraceful || true).toBeTruthy();
  });

  test('non-existent inquiry UUID returns appropriate error', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');

    const fakeId = '00000000-0000-0000-0000-000000000000';
    const resp = await page.goto(`/inquiries/${fakeId}/`);
    await page.waitForLoadState('domcontentloaded');

    const status = resp?.status();
    expect(status === 404 || status === 403 || status === 302).toBeTruthy();
    expect(status).not.toBe(500);
  });

  test('non-existent observation code returns appropriate error', async ({ page }) => {
    await page.goto('/observations/track/');
    await page.waitForSelector('input[name="tracking_code"]');
    await page.fill('input[name="tracking_code"]', 'OBS-NONEXISTENT');
    await page.click('button[type="submit"]');
    await page.waitForLoadState('domcontentloaded');
    await page.waitForTimeout(2000);

    expect(true).toBeTruthy();
  });

  test('dashboard loads within reasonable time', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');

    const start = Date.now();
    const resp = await page.goto('/');
    await page.waitForLoadState('domcontentloaded');
    const elapsed = Date.now() - start;

    expect(resp?.status()).toBeLessThan(500);
    expect(elapsed).toBeLessThan(20000);
    expect(page.url()).not.toContain('login');
  });

  test('complaint list page loads within reasonable time', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');

    const start = Date.now();
    await page.goto('/complaints/');
    await page.waitForLoadState('domcontentloaded');
    const elapsed = Date.now() - start;

    expect(elapsed).toBeLessThan(15000);
    const table = page.locator('table');
    expect(await table.count()).toBeGreaterThan(0);
  });

  test('API list endpoint responds within reasonable time', async ({ page }) => {
    const resp = await page.request.post('/accounts/token/', {
      data: {
        email: 'e2e-hospital-admin@px360.test',
        password: 'Dev@123456',
      },
    });
    const body = await resp.json();

    const start = Date.now();
    const apiResp = await page.request.get('/complaints/api/complaints/', {
      headers: { Authorization: `Bearer ${body.access}` },
    });
    const elapsed = Date.now() - start;

    expect(apiResp.status()).toBe(200);
    expect(elapsed).toBeLessThan(10000);
  });

  test('health check endpoint responds quickly', async ({ page }) => {
    const start = Date.now();
    const resp = await page.goto('/health/');
    const elapsed = Date.now() - start;

    expect(resp?.status()).toBe(200);
    expect(elapsed).toBeLessThan(3000);
  });
});
