import { test, expect } from '@playwright/test';
import { login, navigateTo } from './helpers';
import path from 'path';

test.describe('Document Management', () => {
  test.beforeEach(async ({ page }) => {
    await login(page, 'super_admin');
  });

  test('navigate to documents page', async ({ page }) => {
    await navigateTo(page, '/documents');
    await page.waitForLoadState('networkidle');

    const heading = page.getByText(/documents|files/i).first();
    await expect(heading).toBeVisible({ timeout: 10_000 });
  });

  test('upload a test file via files page', async ({ page }) => {
    // Try the files sub-page which may have a file browser
    await navigateTo(page, '/documents');
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(2000);

    // Look for an upload button
    const uploadBtn = page.getByRole('button', { name: /upload|add/i }).first();
    if (await uploadBtn.isVisible({ timeout: 5_000 }).catch(() => false)) {
      // Check for a file input (may be hidden)
      const fileInput = page.locator('input[type="file"]').first();
      if ((await fileInput.count()) > 0) {
        const testFilePath = path.resolve('tests/e2e/fixtures/test-document.txt');
        await fileInput.setInputFiles(testFilePath);
        await page.waitForTimeout(5000);
      } else {
        // Click the upload button and then look for the input
        await uploadBtn.click();
        await page.waitForTimeout(1000);
        const fileInput2 = page.locator('input[type="file"]').first();
        if ((await fileInput2.count()) > 0) {
          const testFilePath = path.resolve('tests/e2e/fixtures/test-document.txt');
          await fileInput2.setInputFiles(testFilePath);
          await page.waitForTimeout(5000);
        }
      }
    }

    // Verify page didn't crash
    const pageContent = page.getByText(/documents|files/i).first();
    await expect(pageContent).toBeVisible({ timeout: 5_000 });
  });

  test('documents hub shows the EOI queue tab', async ({ page }) => {
    await navigateTo(page, '/documents');
    await page.waitForLoadState('networkidle');

    const tab = page.getByRole('tab', { name: /eoi queue/i });
    await expect(tab).toBeVisible({ timeout: 10_000 });
    await tab.click();
    await expect(tab).toHaveAttribute('data-state', 'active');
  });
});
