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

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

pool.on('error', (err) => {
  console.error('Unexpected error on idle client', err);
  process.exit(-1);
});

async function initDatabase() {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');

    await client.query(`
      CREATE TABLE IF NOT EXISTS 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 client.query(`
      CREATE TABLE IF NOT EXISTS 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 client.query(`
      CREATE TABLE IF NOT EXISTS 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
      )
    `);

    await client.query('COMMIT');
    console.log('Database tables created successfully');
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  } finally {
    client.release();
  }
}

module.exports = { pool, initDatabase };
