import { Pool } from 'pg';
import dotenv from 'dotenv';

dotenv.config();

const pool = new Pool({
  connectionString: process.env.DATABASE_URL
});

const initDb = async (): Promise<void> => {
  try {
    // 1. Users table
    await pool.query(`
      CREATE TABLE IF NOT EXISTS users (
        id SERIAL PRIMARY KEY,
        username VARCHAR(50) UNIQUE NOT NULL,
        email VARCHAR(255) UNIQUE NOT NULL,
        password_hash VARCHAR(255) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )
    `);

    // 2. Beans table
    await pool.query(`
      CREATE TABLE IF NOT EXISTS beans (
        id VARCHAR(50) PRIMARY KEY,
        user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
        name VARCHAR(255) NOT NULL,
        roastery VARCHAR(255),
        tasting_notes TEXT,
        roast_type VARCHAR(50),
        roast_date VARCHAR(50),
        image TEXT,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        is_deleted BOOLEAN DEFAULT FALSE
      )
    `);

    // 3. Brew logs table
    await pool.query(`
      CREATE TABLE IF NOT EXISTS brew_logs (
        id VARCHAR(50) PRIMARY KEY,
        user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
        bean_id VARCHAR(50) REFERENCES beans(id) ON DELETE CASCADE,
        method VARCHAR(50),
        grind VARCHAR(100),
        water_temp VARCHAR(50),
        ratio VARCHAR(50),
        yield VARCHAR(50),
        time VARCHAR(50),
        notes TEXT,
        rating INTEGER,
        created_at BIGINT,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        is_deleted BOOLEAN DEFAULT FALSE
      )
    `);
    console.log('Database initialized');
  } catch (err) {
    console.error('Error initializing database', err);
  }
};

initDb();

export default pool;
