const { Client, Pool } = require('pg');

async function setup() {
  try {
    const adminClient = new Client({
      host: '192.168.21.197',
      port: 5432,
      user: 'postgres',
      password: 'BJg6a540CmSaO8',
      database: 'postgres'
    });
    await adminClient.connect();

    const dbExists = await adminClient.query(
      "SELECT 1 FROM pg_database WHERE datname = 'casino_crawler'"
    );
    if (dbExists.rows.length === 0) {
      console.log('Creating database: casino_crawler');
      await adminClient.query('CREATE DATABASE casino_crawler');
    } else {
      console.log('Database already exists');
    }

    const appPool = new Pool({
      host: '192.168.21.197',
      port: 5432,
      user: 'postgres',
      password: 'BJg6a540CmSaO8',
      database: 'casino_crawler'
    });

    const pool = await appPool.connect();

    // Drop and recreate tables (fresh start)
    await pool.query('DROP TABLE IF EXISTS casinos CASCADE');
    await pool.query('DROP TABLE IF EXISTS crawls CASCADE');
    await pool.query('DROP TABLE IF EXISTS users CASCADE');

    // Create tables
    await pool.query(`
      CREATE TABLE crawls (
        id SERIAL PRIMARY KEY,
        url TEXT NOT NULL,
        site_name VARCHAR(255),
        crawled_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        status VARCHAR(50) DEFAULT 'pending',
        screenshot_path TEXT
      )
    `);

    await pool.query(`
      CREATE TABLE casinos (
        id SERIAL PRIMARY KEY,
        crawl_id INTEGER REFERENCES crawls(id) ON DELETE CASCADE,
        position INTEGER NOT NULL,
        casino_name VARCHAR(255),
        url TEXT,
        bonus_offer TEXT,
        favicon_url TEXT
      )
    `);

    await pool.query(`
      CREATE TABLE users (
        id SERIAL PRIMARY KEY,
        username VARCHAR(100) UNIQUE NOT NULL,
        password_hash VARCHAR(255) NOT NULL,
        role VARCHAR(50) DEFAULT 'admin',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )
    `);

    // Create default admin user
    const bcrypt = require('bcryptjs');
    const defaultPassword = await bcrypt.hash('admin123', 12);
    
    await pool.query(
      'INSERT INTO users (username, password_hash, role) VALUES ($1, $2, $3) ON CONFLICT (username) DO NOTHING',
      ['admin', defaultPassword, 'admin']
    );

    console.log('Database setup complete!');
    console.log('Default admin credentials:');
    console.log('  Username: admin');
    console.log('  Password: admin123');
    
    process.exit(0);
  } catch (error) {
    console.error('Error setting up database:', error);
    process.exit(1);
  }
}

setup();
