import { execSync } from 'child_process';
import 'dotenv/config';

async function globalSetup() {
  console.log('\n🚀 Starting E2E Live Environment Global Setup...');

  if (!process.env.TEST_DATABASE_URL) {
    console.error('❌ TEST_DATABASE_URL is not set in environment blocks live E2E tests to protect dev data.');
    process.exit(1);
  }

  if (!process.env.TEST_DISCORD_TOKEN) {
    console.error('❌ TEST_DISCORD_TOKEN is missing. Live E2E tests require a bot token to simulate discord interactions.');
    process.exit(1);
  }

  // Set the global database to the test specific one
  process.env.DATABASE_URL = process.env.TEST_DATABASE_URL;

  try {
    console.log(`📦 Pushing Test Schema to ${process.env.TEST_DATABASE_URL}...`);
    // Run prisma db push in packages/db
    // Using string replacement or passing env dynamically
    execSync('yarn workspace @kord/db run prisma db push --accept-data-loss', {
      stdio: 'inherit',
      env: { ...process.env, DATABASE_URL: process.env.TEST_DATABASE_URL }
    });

    console.log(`🌱 Seeding Test Data...`);
    execSync('yarn workspace @kord/db run prisma db seed', {
      stdio: 'inherit',
      env: { ...process.env, DATABASE_URL: process.env.TEST_DATABASE_URL }
    });

    console.log('✅ Global Setup Complete!\n');
  } catch (error) {
    console.error('❌ Failed to push schema or seed test database:', error);
    process.exit(1);
  }
}

export default globalSetup;
