// src/tests/setup/global-setup.ts
import { Pool } from 'pg';
import fs from 'node:fs/promises';
import path from 'path';
import { execSync } from 'child_process';

const getPool = () => {
  // This pool connects using the test-specific environment variables
  // passed from the Gitea workflow (e.g., DB_NAMEyer-crawler-test").
  return new Pool({
    user: process.env.DB_USER,
    host: process.env.DB_HOST,
    database: process.env.DB_NAME,
    password: process.env.DB_PASSWORD,
    port: parseInt(process.env.DB_PORT || '5432', 10),
  });
};

/**
 * This function is executed once before all tests.
 * It connects to the permanent test database, wipes the public schema,
 * and then rebuilds it from the master rollup script.
 */
export async function setup() {
  // --- START DEBUG LOGGING ---
  // Log the database connection details being used by the Vitest GLOBAL SETUP process.
  // These variables are inherited from the CI environment.
  console.log('\n\n--- [GLOBAL SETUP LOG] DATABASE CONNECTION ---');
  console.log(`  Host: ${process.env.DB_HOST}`);
  console.log(`  Port: ${process.env.DB_PORT}`);
  console.log(`  User: ${process.env.DB_USER}`);
  console.log(`  Database: ${process.env.DB_NAME}`);
  console.log('-------------------------------------------\n');
  // --- END DEBUG LOGGING ---
  console.log('\nResetting test database schema...');
  const pool = getPool();

  try {
    // 1. Drop the entire public schema to ensure a clean slate.
    const dropScriptPath = path.resolve(process.cwd(), 'sql/drop_tables.sql');
    const dropSql = await fs.readFile(dropScriptPath, 'utf-8');
    await pool.query(dropSql);
    console.log('✅ Public schema dropped successfully.');

    // 2. Apply the master database schema to create all tables, functions, and triggers.
    const schemaPath = path.resolve(process.cwd(), 'sql/master_schema_rollup.sql');
    const schemaSql = await fs.readFile(schemaPath, 'utf-8');
    await pool.query(schemaSql);
    console.log('✅ Test database schema rebuilt successfully.');

    // 3. Seed the essential admin account needed for integration tests.
    console.log('Seeding admin account...');
    // Use `tsx` instead of `ts-node` for more reliable TypeScript execution in a child process,
    // as it's already a project dependency and handles module resolution correctly.
    execSync('npx tsx src/db/seed_admin_account.ts');
    console.log('✅ Admin account seeded successfully.');
  } catch (error) {
    console.error('🔴 Error applying database schema:', error);
    // Exit immediately if schema setup fails, as tests cannot run.
    process.exit(1);
  } finally {
    await pool.end();
  }
}

/**
 * This function is executed once after all tests have completed.
 */
export async function teardown() {
  console.log('\n✅ Test database integration tests finished.');
}