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

function authenticate(page: Page) {
  return page.addInitScript(() => {
    localStorage.setItem('admin_access_token', 'mock-token');
    localStorage.setItem('admin_refresh_token', 'mock-refresh');
    localStorage.setItem(
      'admin_auth_user',
      JSON.stringify({
        email: 'admin@example.com',
        name: 'Admin User',
        role: 'super_admin',
      })
    );
  });
}

async function fulfillJson(route: Route, body: unknown, status = 200) {
  await route.fulfill({
    status,
    contentType: 'application/json',
    body: JSON.stringify(body),
  });
}

test.describe('Admin dashboard reliability', () => {
  test('shows an in-page retry path when dashboard APIs fail', async ({ page }) => {
    await authenticate(page);

    let recover = false;
    await page.route('**/api/dashboard/stats', route =>
      recover
        ? fulfillJson(route, {
            users: { total: 42, byPlan: { pro: 20 } },
            tokens: { active: 7 },
            usage: { totalWords: 8400, totalDictations: 120, totalCost: 12.34 },
            audit: { total: 2, failedLogins: 0 },
          })
        : fulfillJson(route, { error: 'stats unavailable' }, 503)
    );
    await page.route('**/api/usage**', route =>
      recover
        ? fulfillJson(route, {
            records: [
              {
                date: '2026-05-30',
                tokensUsed: 8400,
                dictations: 120,
                costUsd: 12.34,
                model: 'gpt-4o-mini',
              },
            ],
          })
        : fulfillJson(route, { error: 'usage unavailable' }, 503)
    );
    await page.route('**/api/users**', route =>
      recover
        ? fulfillJson(route, {
            users: [
              {
                id: 'u1',
                name: 'Admin User',
                email: 'admin@example.com',
                plan: 'pro',
                status: 'active',
                createdAt: '2026-05-01T00:00:00Z',
                lastActive: '2026-05-30T00:00:00Z',
                totalTokensUsed: 8400,
                totalRequests: 120,
                monthlySpend: 12.34,
              },
            ],
            total: 1,
            byPlan: { pro: 1 },
          })
        : fulfillJson(route, { error: 'users unavailable' }, 503)
    );
    await page.route('**/api/analytics/revenue**', route =>
      recover
        ? fulfillJson(route, {
            mrr: 199,
            arr: 2388,
            mrrChange: 8,
            totalRevenue: 2388,
            revenueByMonth: [],
            churnRate: 2,
            churnCount: 1,
            ltv: 1200,
            arpu: 99,
            newSubscriptions: 3,
            canceledSubscriptions: 1,
          })
        : fulfillJson(route, { error: 'revenue unavailable' }, 503)
    );

    await page.goto('/');
    const errorHeading = page.getByRole('heading', { name: /could not load dashboard/i });
    const recoveredKpi = page.getByText('42', { exact: true }).first();

    await expect(errorHeading.or(recoveredKpi)).toBeVisible();
    if (await errorHeading.isVisible().catch(() => false)) {
      recover = true;
      await page.getByRole('button', { name: /retry/i }).click();
    }

    await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
    await expect(recoveredKpi).toBeVisible();
    await expect(page.getByRole('main').getByText('Admin User')).toBeVisible();
  });
});
