/**
 * API Authentication Setup for E2E Tests
 * 
 * This setup creates authentication sessions for both regular and admin users
 * that are persisted across all tests in the suite.
 */

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

const API_BASE_URL = process.env.API_BASE_URL ?? process.env.NEXT_PUBLIC_API_BASE_URL ?? 'http://localhost:3101';

// Define auth file paths
const USER_AUTH_FILE = path.join(__dirname, '.auth/user-session.json');
const ADMIN_AUTH_FILE = path.join(__dirname, '.auth/admin-session.json');

setup('Authenticate regular user', async ({ request }) => {
  console.log(`[AUTH SETUP] Creating regular user session at: ${API_BASE_URL}`);
  
  // Wait for API to be ready
  const maxAttempts = 30;
  let apiReady = false;
  
  for (let i = 0; i < maxAttempts; i++) {
    try {
      const response = await request.get(`${API_BASE_URL}/health`);
      if (response.ok()) {
        apiReady = true;
        console.log(`[AUTH SETUP] API is ready after ${i + 1} attempts`);
        break;
      }
    } catch (error) {
      // Continue trying
    }
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
  
  if (!apiReady) {
    throw new Error('API failed to become ready');
  }

  // Create test user and establish cookie-based session
  const testEmail = `smoke-test-${Date.now()}@example.com`;
  const testPassword = 'Password123';
  
  // Signup
  const signupResponse = await request.post(`${API_BASE_URL}/auth/signup`, {
    data: {
      email: testEmail,
      password: testPassword,
      displayName: 'Smoke Tester',
      username: `smokeuser${Date.now()}`
    }
  });
  
  if (!signupResponse.ok()) {
    throw new Error(`Signup failed: ${signupResponse.status()}`);
  }
  
  const signupData = await signupResponse.json();
  const testUserId = signupData?.user?.userId ?? null;
  console.log('[AUTH SETUP] Test user created:', testUserId);
  
  // Login to establish cookie session
  const loginResponse = await request.post(`${API_BASE_URL}/auth/login`, {
    data: {
      email: testEmail,
      password: testPassword
    }
  });
  
  if (!loginResponse.ok()) {
    throw new Error(`Login failed: ${loginResponse.status()}`);
  }
  
  console.log('[AUTH SETUP] Regular user session established');

  // Get cookies and save to auth file
  const context = request.context();
  const cookies = context.cookies();
  
  // Ensure auth directory exists
  await fs.mkdir(path.dirname(USER_AUTH_FILE), { recursive: true });
  
  // Save cookies to file
  await fs.writeFile(USER_AUTH_FILE, JSON.stringify({ cookies }, null, 2));
  console.log(`[AUTH SETUP] Saved user session to: ${USER_AUTH_FILE}`);
});

setup('Authenticate admin user', async ({ request }) => {
  console.log(`[AUTH SETUP] Creating admin user session at: ${API_BASE_URL}`);
  
  // Use seeded admin credentials
  const adminEmail = 'demo.admin@example.com';
  const adminPassword = 'Demo1234!';
  
  // Login as admin
  const loginResponse = await request.post(`${API_BASE_URL}/auth/login`, {
    data: {
      email: adminEmail,
      password: adminPassword
    }
  });
  
  if (!loginResponse.ok()) {
    throw new Error(`Admin login failed: ${loginResponse.status()}`);
  }
  
  console.log('[AUTH SETUP] Admin user session established');

  // Get cookies and save to auth file
  const context = request.context();
  const cookies = context.cookies();
  
  // Ensure auth directory exists
  await fs.mkdir(path.dirname(ADMIN_AUTH_FILE), { recursive: true });
  
  // Save cookies to file
  await fs.writeFile(ADMIN_AUTH_FILE, JSON.stringify({ cookies }, null, 2));
  console.log(`[AUTH SETUP] Saved admin session to: ${ADMIN_AUTH_FILE}`);
});