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

const ADMIN_EMAIL = process.env.E2E_ADMIN_EMAIL ?? 'admin@example.com';
const ADMIN_PASSWORD = process.env.E2E_ADMIN_PASSWORD ?? 'Admin123!';

test.describe('Auth', () => {
  test('login succeeds and shows dashboard', async ({ page }) => {
    await page.goto('/login');
    await page.locator('#email').fill(ADMIN_EMAIL);
    await page.locator('#password').fill(ADMIN_PASSWORD);
    await page.getByRole('button', { name: 'Sign in' }).click();
    await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible({ timeout: 15_000 });
    await expect(page).toHaveURL(/\/$/);
  });

  test('login fails with invalid credentials', async ({ page }) => {
    await page.goto('/login');
    await page.locator('#email').fill('invalid-user@example.com');
    await page.locator('#password').fill('wrong-password');
    await page.getByRole('button', { name: 'Sign in' }).click();
    await expect(page.getByText('Invalid email or password')).toBeVisible({ timeout: 10_000 });
    await expect(page).toHaveURL(/\/login/);
  });
});

/** API base for request-context login (avoids CORS when UI runs on a different dev port than production). */
const API_BASE = process.env.PLAYWRIGHT_API_URL ?? 'http://localhost:3001';

async function loginViaApiAndSeedStorage(page: import('@playwright/test').Page) {
  const res = await page.request.post(`${API_BASE}/api/v1/auth/login`, {
    data: { email: ADMIN_EMAIL, password: ADMIN_PASSWORD },
  });
  if (!res.ok()) {
    throw new Error(`API login failed: ${res.status()} ${await res.text()}`);
  }
  const body = (await res.json()) as { token: string };
  await page.goto('/login');
  await page.evaluate((t) => {
    localStorage.setItem('token', t);
  }, body.token);
}

test.describe('Companies', () => {
  test.beforeEach(async ({ page }) => {
    await loginViaApiAndSeedStorage(page);
  });

  test('Companies page loads (direct navigation)', async ({ page }, testInfo) => {
    await page.goto('/companies', { waitUntil: 'domcontentloaded' });
    // Let client router settle (stale Docker UI redirects /companies → /).
    await page.waitForTimeout(1500);
    const href = page.url();
    const stayedOnCompanies = /\/companies/.test(href);
    if (!stayedOnCompanies) {
      test.skip();
      return;
    }
    await expect(page).toHaveURL(/\/companies/);
    await expect(page.getByRole('heading', { name: 'Companies', exact: true })).toBeVisible({ timeout: 15_000 });
    await expect(page.getByText('Add company')).toBeVisible();
    await page.screenshot({ path: path.join(testInfo.outputDir, 'companies-page.png'), fullPage: true });
  });
});

test.describe('Channels', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/login');
    await page.locator('#email').fill(ADMIN_EMAIL);
    await page.locator('#password').fill(ADMIN_PASSWORD);
    await page.getByRole('button', { name: 'Sign in' }).click();
    await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible({ timeout: 15_000 });
  });

  test('channels list loads and channel detail opens', async ({ page }) => {
    await page.goto('/channels');
    await expect(page.getByRole('heading', { name: 'Channels' })).toBeVisible({ timeout: 15_000 });
    const firstCardLink = page.locator('a[href^="/channels/"]').first();
    const count = await firstCardLink.count();
    if (count === 0) {
      test.skip();
      return;
    }
    await firstCardLink.click();
    // Detail page shows skeletons until GET /channels/:id completes
    await expect(page.getByText('Onboarding (WhatsApp)')).toBeVisible({ timeout: 20_000 });
  });
});
