import { test as setup } from '@playwright/test';
import path from 'path';

const authFile = path.join(process.cwd(), 'tests/playwright/.auth/user.json');

const DEMO_EMAIL = process.env.TEST_EMAIL ?? 'demo@mini-ecd.demo';
const DEMO_PASSWORD = process.env.TEST_PASSWORD ?? 'Demo2024!';
const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const SUPABASE_ANON_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;

setup('authenticate as demo user', async ({ page, request }) => {
  // Authenticate via Supabase REST API - faster and more reliable than UI form
  const response = await request.post(`${SUPABASE_URL}/auth/v1/token?grant_type=password`, {
    headers: {
      apikey: SUPABASE_ANON_KEY,
      'Content-Type': 'application/json',
    },
    data: { email: DEMO_EMAIL, password: DEMO_PASSWORD },
  });

  if (!response.ok()) {
    throw new Error(`Supabase auth failed: ${response.status()} ${await response.text()}`);
  }

  const tokenData = await response.json();

  // Build Supabase auth cookie (format: base64-<base64 encoded JSON>)
  const projectRef = SUPABASE_URL.replace('https://', '').split('.')[0];
  const cookieName = `sb-${projectRef}-auth-token`;
  const cookieValue = `base64-${Buffer.from(JSON.stringify(tokenData)).toString('base64')}`;

  await page.context().addCookies([
    {
      name: cookieName,
      value: cookieValue,
      domain: 'localhost',
      path: '/',
      httpOnly: false,
      secure: false,
      sameSite: 'Lax',
    },
  ]);

  // Verify the session works by navigating to a protected route
  await page.goto('/epd/cortex');
  await page.waitForURL(/\/epd\//, { timeout: 15_000 });

  await page.context().storageState({ path: authFile });
});
