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

test.describe('Session Auth Edge Cases', () => {

  test('expired session redirects to login', async ({ browser }) => {
    const context = await browser.newContext();
    const page = await context.newPage();

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

    await page.goto('/');
    await page.waitForLoadState('domcontentloaded');
    expect(await page.url()).not.toContain('/accounts/login/');

    await context.clearCookies();

    await page.goto('/complaints/');
    await page.waitForLoadState('domcontentloaded');
    expect(await page.url()).toContain('/accounts/login/');

    await context.close();
  });

  test('simultaneous sessions both work', async ({ browser }) => {
    const ctx1 = await browser.newContext();
    const ctx2 = await browser.newContext();
    const page1 = await ctx1.newPage();

    const auth1 = new RoleAuthHelper(page1);
    await auth1.login('hospital_admin');

    await page1.goto('/complaints/');
    await page1.waitForLoadState('domcontentloaded');

    expect(await page1.textContent('body')).toBeTruthy();

    await ctx1.close();
    await ctx2.close();
  });

  test('deactivated user mid-session shows error on next login', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('staff');

    await page.goto('/');
    await page.waitForLoadState('domcontentloaded');
    expect(await page.url()).not.toContain('/accounts/login/');

    await auth.logout();
    await page.waitForLoadState('domcontentloaded');

    await auth.login('staff');
    expect(await page.url()).not.toContain('/accounts/login/');
  });

  test('logout clears session and redirects', async ({ page }) => {
    const auth = new RoleAuthHelper(page);
    await auth.login('hospital_admin');

    await page.goto('/');
    await page.waitForLoadState('domcontentloaded');
    expect(await page.url()).not.toContain('/accounts/login/');

    await auth.logout();
    expect(await page.url()).toContain('/accounts/login/');
  });

  test('protected page without session redirects to login', async ({ page }) => {
    await page.goto('/complaints/');
    await page.waitForLoadState('domcontentloaded');
    expect(await page.url()).toContain('/accounts/login/');
  });
});
