// apps/web/e2e/check-readiness.ts
import type { FullConfig } from '@playwright/test';

async function check(url: string, label: string): Promise<void> {
  for (let i = 0; i < 5; i++) {
    try {
      const res = await fetch(url);
      if (res.ok) return;
    } catch { /* retry */ }
    console.log(`⏳ ${label} 未就绪，等待重试 (${i + 1}/5)...`);
    await new Promise((r) => setTimeout(r, 2000));
  }
  throw new Error(`❌ ${label} 未就绪: ${url}。请确认后端服务已启动 (cd crates/erp-server && cargo run)`);
}

export default async function globalSetup(_config: FullConfig) {
  const apiBase = process.env.E2E_API_URL || 'http://localhost:3000';
  const webBase = process.env.E2E_BASE_URL || 'http://localhost:5174';
  await check(`${apiBase}/api/v1/health`, '后端 API');
  await check(webBase, '前端 SPA');
  console.log('✅ E2E 环境就绪');
}
