/**
 * Manual Test Database Setup Script
 *
 * This script helps set up the test database when Docker is not available.
 * It can connect to any PostgreSQL instance and prepare it for E2E testing.
 *
 * Usage:
 *   npx ts-node scripts/setup-test-db.ts
 *
 * Environment variables (or set in .env.test):
 *   DATABASE_URL - PostgreSQL connection string
 */

import { execSync } from 'child_process';
import * as path from 'path';
import * as dotenv from 'dotenv';

// Load test environment
dotenv.config({ path: path.resolve(__dirname, '../.env.test') });

async function main() {
  console.log('🔧 Manual Test Database Setup');
  console.log('============================\n');

  const databaseUrl = process.env.DATABASE_URL;

  if (!databaseUrl) {
    console.error('❌ DATABASE_URL environment variable is not set');
    console.log('\nPlease set DATABASE_URL in .env.test or as an environment variable');
    console.log('Example: DATABASE_URL="postgresql://postgres:password@localhost:5432/rwa_backup_test"');
    process.exit(1);
  }

  console.log(`📌 Database URL: ${databaseUrl.replace(/:[^:@]+@/, ':****@')}\n`);

  // Test database connection
  console.log('⏳ Testing database connection...');
  try {
    const { Client } = await import('pg');
    const client = new Client({ connectionString: databaseUrl });
    await client.connect();
    const result = await client.query('SELECT version()');
    console.log(`✅ Connected to PostgreSQL: ${result.rows[0].version.split(',')[0]}\n`);
    await client.end();
  } catch (error: any) {
    console.error(`❌ Failed to connect to database: ${error.message}`);
    console.log('\nMake sure:');
    console.log('  1. PostgreSQL is running');
    console.log('  2. The database exists');
    console.log('  3. The credentials are correct');
    process.exit(1);
  }

  // Push Prisma schema
  console.log('🔄 Pushing Prisma schema to database...');
  try {
    execSync('npx prisma db push --force-reset --accept-data-loss', {
      cwd: path.resolve(__dirname, '..'),
      stdio: 'inherit',
      env: {
        ...process.env,
        DATABASE_URL: databaseUrl,
      },
    });
    console.log('');
  } catch (error) {
    console.error('❌ Failed to push Prisma schema');
    process.exit(1);
  }

  // Generate Prisma client
  console.log('🔧 Generating Prisma client...');
  try {
    execSync('npx prisma generate', {
      cwd: path.resolve(__dirname, '..'),
      stdio: 'inherit',
    });
    console.log('');
  } catch (error) {
    console.error('❌ Failed to generate Prisma client');
    process.exit(1);
  }

  console.log('✅ Test database setup complete!\n');
  console.log('You can now run E2E tests with:');
  console.log('  USE_DOCKER=false npm run test:e2e:db\n');
}

main().catch(console.error);
