/**
 * Test connection and setup database
 */
import { Pool } from 'pg';
import dotenv from 'dotenv';

dotenv.config();

const localDbConfig = {
  host: process.env.LOCAL_DB_HOST || '192.168.8.151',
  port: parseInt(process.env.LOCAL_DB_PORT || '5432'),
  user: process.env.LOCAL_DB_USER || 'postgres',
  password: process.env.LOCAL_DB_PASSWORD || 'postgres',
  database: process.env.LOCAL_DB_NAME || 'institutional_trader'
};

async function main() {
  console.log('🔍 Testing PostgreSQL connection...');
  console.log(`   Host: ${localDbConfig.host}:${localDbConfig.port}`);
  console.log(`   User: ${localDbConfig.user}`);
  console.log(`   Database: ${localDbConfig.database}\n`);

  // Test connection to postgres database first
  const adminPool = new Pool({
    host: localDbConfig.host,
    port: localDbConfig.port,
    user: localDbConfig.user,
    password: localDbConfig.password,
    database: 'postgres'
  });

  try {
    await adminPool.query('SELECT 1');
    console.log('✅ Connected to PostgreSQL server\n');
  } catch (error) {
    console.error('❌ Cannot connect to PostgreSQL:', error.message);
    console.error('\nPlease check:');
    console.error('1. PostgreSQL is running');
    console.error('2. .env file has correct LOCAL_DB_PASSWORD');
    process.exit(1);
  } finally {
    await adminPool.end();
  }

  // Create database if needed
  const createDbPool = new Pool({
    host: localDbConfig.host,
    port: localDbConfig.port,
    user: localDbConfig.user,
    password: localDbConfig.password,
    database: 'postgres'
  });

  try {
    const dbCheck = await createDbPool.query(
      `SELECT 1 FROM pg_database WHERE datname = $1`,
      [localDbConfig.database]
    );

    if (dbCheck.rows.length === 0) {
      console.log(`📦 Creating database: ${localDbConfig.database}...`);
      await createDbPool.query(`CREATE DATABASE ${localDbConfig.database}`);
      console.log('✅ Database created\n');
    } else {
      console.log('✅ Database already exists\n');
    }
  } catch (error) {
    console.error('❌ Error with database:', error.message);
    process.exit(1);
  } finally {
    await createDbPool.end();
  }

  // Connect to our database and create tables
  const pool = new Pool({
    host: localDbConfig.host,
    port: localDbConfig.port,
    user: localDbConfig.user,
    password: localDbConfig.password,
    database: localDbConfig.database
  });

  try {
    console.log('📋 Creating tables...');

    // OptionsFlow_monthly
    await pool.query(`
      CREATE TABLE IF NOT EXISTS "OptionsFlow_monthly" (
        "CreatedDate" TEXT,
        "CreatedTime" TEXT,
        "Symbol" TEXT,
        "Type" TEXT,
        "Volume" TEXT,
        "Price" TEXT,
        "Side" TEXT,
        "CallPut" TEXT,
        "Strike" TEXT,
        "Spot" TEXT,
        "Premium" TEXT,
        "ExpirationDate" TEXT,
        "Color" TEXT,
        "ImpliedVolatility" TEXT,
        "Dte" TEXT,
        "ER" TEXT,
        "StockEtf" TEXT,
        "Sector" TEXT,
        "Uoa" TEXT,
        "Weekly" TEXT,
        "MktCap" TEXT,
        "OI" TEXT
      );
    `);
    console.log('   ✅ OptionsFlow_monthly');

    // OptionsVolume
    await pool.query(`
      CREATE TABLE IF NOT EXISTS "OptionsVolume" (
        "SYMBOL" TEXT,
        "VOL" NUMERIC,
        "C VOL" NUMERIC,
        "P VOL" NUMERIC,
        "P/C" NUMERIC,
        "AVG VOL" NUMERIC,
        "RATIO" NUMERIC,
        "COI" NUMERIC,
        "POI" NUMERIC,
        "DCOI" NUMERIC,
        "DPOI" NUMERIC
      );
    `);
    console.log('   ✅ OptionsVolume');

    // OptionsOpenInterest
    await pool.query(`
      CREATE TABLE IF NOT EXISTS "OptionsOpenInterest" (
        "SYMBOL" TEXT,
        "EXP" TEXT,
        "C/P" TEXT,
        "STRIKE" NUMERIC,
        "OI" NUMERIC,
        "DOI" NUMERIC
      );
    `);
    console.log('   ✅ OptionsOpenInterest');

    // AlertStream_monthly
    await pool.query(`
      CREATE TABLE IF NOT EXISTS "AlertStream_monthly" (
        "date" TEXT,
        "timestamp" TEXT,
        "ticker" TEXT,
        "type" TEXT,
        "message" TEXT,
        "price" NUMERIC,
        "volume" NUMERIC
      );
    `);
    console.log('   ✅ AlertStream_monthly');

    // Prices tables
    await pool.query(`
      CREATE TABLE IF NOT EXISTS prices_intraday_1m (
        symbol TEXT,
        ts TIMESTAMP WITH TIME ZONE,
        open NUMERIC,
        high NUMERIC,
        low NUMERIC,
        close NUMERIC,
        volume NUMERIC
      );
    `);
    console.log('   ✅ prices_intraday_1m');

    await pool.query(`
      CREATE TABLE IF NOT EXISTS prices_daily (
        symbol TEXT,
        "Date" DATE,
        open NUMERIC,
        high NUMERIC,
        low NUMERIC,
        close NUMERIC,
        volume NUMERIC
      );
    `);
    console.log('   ✅ prices_daily');

    console.log('\n✅ All tables created successfully!');
    console.log('\n📥 Ready to import CSV files. Run: npm run import-csv');

  } catch (error) {
    console.error('❌ Error:', error.message);
    process.exit(1);
  } finally {
    await pool.end();
  }
}

main().catch(console.error);

