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 to console' }).click();
    await expect(page.getByRole('banner').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 to console' }).click();
    await expect(page.getByText('Invalid email or password')).toBeVisible({ timeout: 10_000 });
    await expect(page).toHaveURL(/\/login/);
  });
});

/** API base for request-context login (set in playwright.config from API_HOST_PORT / .env). */
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.getByText('Add a client')).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 to console' }).click();
    await expect(page.getByRole('banner').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('banner').getByRole('heading', { name: 'Channels' })).toBeVisible({
      timeout: 15_000,
    });
    // Portal channel is listed first and shows "Onboarding (inherited)" — target a WhatsApp number link.
    await expect(page.locator('a[href^="/channels/"]').first()).toBeVisible({ timeout: 15_000 });
    const waLink = page.locator('a[href^="/channels/"]').filter({ hasText: /\+\d/ }).first();
    const count = await waLink.count();
    if (count === 0) {
      test.skip();
      return;
    }
    await waLink.click();
    // Detail page shows skeletons until GET /channels/:id completes
    await expect(page.getByText('Onboarding (WhatsApp)')).toBeVisible({ timeout: 20_000 });
  });

  test('add WhatsApp offers provider choices and Africa\'s Talking avoids QR', async ({ page }) => {
    await page.goto('/channels');
    await page.getByRole('button', { name: 'Add WhatsApp' }).click();
    await expect(page.getByRole('radio', { name: /Baileys \/ QR/ })).toBeVisible();
    const at = page.getByRole('radio', { name: /Africa's Talking/ });
    await expect(at).toBeVisible();
    await at.check();
    const create = page.getByRole('button', { name: /^Create/ });
    await expect(create).toBeVisible();
    await expect(create).not.toContainText('QR');
  });
});
