const { Pool } = require('pg');
require('dotenv').config();
const fs = require('fs');
const path = require('path');
const bcrypt = require('bcryptjs');

const initDb = async () => {
    // First connect to default 'postgres' db to create 'car_rental'
    const tempPool = new Pool({
        user: process.env.DB_USER,
        host: process.env.DB_HOST,
        database: 'postgres',
        password: process.env.DB_PASSWORD,
        port: process.env.DB_PORT,
    });

    try {
        await tempPool.query('CREATE DATABASE car_rental');
        console.log('Database car_rental created.');
    } catch (err) {
        if (err.code === '42P04') {
            console.log('Database car_rental already exists.');
        } else {
            console.error('Error creating database:', err.message, err.stack);
        }
    } finally {
        await tempPool.end();
    }

    try {
        const schema = fs.readFileSync(path.join(__dirname, 'schema.sql'), 'utf8');
        const pool = new Pool({
            user: process.env.DB_USER,
            host: process.env.DB_HOST,
            database: process.env.DB_NAME,
            password: process.env.DB_PASSWORD,
            port: process.env.DB_PORT,
        });
        await pool.query(schema);
        console.log('Tables created successfully.');

        // Check if admin exists
        const adminCheck = await pool.query('SELECT * FROM users WHERE email = $1', ['admin@carrental.com']);

        if (adminCheck.rows.length === 0) {
            const hashedPassword = await bcrypt.hash('admin123', 10);
            await pool.query(
                'INSERT INTO users (name, email, password, role) VALUES ($1, $2, $3, $4)',
                ['System Admin', 'admin@carrental.com', hashedPassword, 'admin']
            );
            console.log('Admin user created (admin@carrental.com / admin123).');
        }

        // Add some demo cars if none exist
        const carCheck = await pool.query('SELECT * FROM cars');
        if (carCheck.rows.length === 0) {
            const demoCars = [
                ['Tesla', 'Model S', 2023, 150.00, 'available'],
                ['BMW', 'M4', 2022, 120.00, 'available'],
                ['Audi', 'A6', 2023, 100.00, 'available'],
                ['Mercedes', 'C-Class', 2022, 95.00, 'available']
            ];

            for (const car of demoCars) {
                await pool.query(
                    'INSERT INTO cars (brand, model, year, price_per_day, status) VALUES ($1, $2, $3, $4, $5)',
                    car
                );
            }
            console.log('Demo cars added.');
        }

        process.exit(0);
    } catch (err) {
        console.error('Error initializing database:', err);
        process.exit(1);
    }
};

initDb();
