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

test.describe('Admin Auth Split', () => {
  test('blocks external identities on internal management login', async ({ page }) => {
    await page.route('**/api/auth/login', async (route) => {
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({
          success: true,
          audience: 'public',
          user: {
            audience: 'public',
            user_type: 'external_user',
          },
        }),
      });
    });

    await page.goto('/login');
    await expect(page.getByRole('heading', { name: /sign in/i })).toBeVisible();
    await page.getByPlaceholder('Enter your email').fill('external.user@example.com');
    await page.getByPlaceholder('Enter your password').fill('StrongPass123!');
    await page.getByRole('button', { name: /sign in/i }).click();

    await expect(page.getByText('External users cannot use this portal.')).toBeVisible();
    await expect(page).toHaveURL(/\/login/);
  });

  test('allows internal identities and lands on admin shell', async ({ page }) => {
    await page.context().addCookies([
      {
        name: 'nxtgauge_admin_session',
        value: 'internal_management',
        domain: '127.0.0.1',
        path: '/',
      },
    ]);

    await page.route('**/api/auth/session**', async (route) => {
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({
          id: 'admin-1',
          audience: 'admin',
          full_name: 'Admin User',
          active_role: 'SUPER_ADMIN',
        }),
      });
    });
    await page.route('**/api/runtime-config**', async (route) => {
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({ active_role: 'SUPER_ADMIN', allowed_modules: [] }),
      });
    });

    await page.goto('/admin');
    await expect(page).toHaveURL(/\/admin/);
  });

  test('keeps admin shell when cookie session exists even if session payload is external', async ({ page }) => {
    await page.context().addCookies([
      {
        name: 'nxtgauge_admin_session',
        value: 'internal_management',
        domain: '127.0.0.1',
        path: '/',
      },
    ]);

    await page.route('**/api/auth/session**', async (route) => {
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({
          audience: 'public',
          user_type: 'external_user',
        }),
      });
    });

    await page.goto('/admin');
    await expect(page).toHaveURL(/\/admin/);
  });
});
