require('dotenv').config();
const sqlite3 = require('sqlite3').verbose();
const path = require('path');
const STORAGE_ROOT = (process.env.STORAGE_VOL_PATH || '').trim();
if (!STORAGE_ROOT) {
    throw new Error('STORAGE_VOL_PATH must be set');
}
const DB_PATH = path.join(STORAGE_ROOT, 'sq_battles.db');

console.log(`Opening database at: ${DB_PATH}`);

const db = new sqlite3.Database(DB_PATH, sqlite3.OPEN_READWRITE, (err) => {
    if (err) {
        console.error('Failed to open database:', err.message);
        process.exit(1);
    }
    console.log('Connected to database successfully');
    
    const checkIndexQuery = `
        SELECT name FROM sqlite_master 
        WHERE type='index' AND name='idx_endtime_unix'
    `;
    
    db.get(checkIndexQuery, [], (err, row) => {
        if (err) {
            console.error('Error checking for existing index:', err.message);
            db.close();
            process.exit(1);
        }
        
        if (row) {
            console.log('Index idx_endtime_unix already exists');
            db.close();
            console.log('Nothing to do - exiting');
            process.exit(0);
        }
        
        console.log('Creating index idx_endtime_unix on player_games_hist(endtime_unix)...');
        const createIndexQuery = `CREATE INDEX idx_endtime_unix ON player_games_hist(endtime_unix)`;
        
        db.run(createIndexQuery, [], (err) => {
            if (err) {
                console.error('Failed to create index:', err.message);
                db.close();
                process.exit(1);
            }
            
            console.log('Index created successfully!');
            
            db.get(checkIndexQuery, [], (err, row) => {
                if (err) {
                    console.error('Error verifying index:', err.message);
                } else if (row) {
                    console.log('Index verified successfully');
                } else {
                    console.warn('Warning: Index not found after creation');
                }
                
                db.close((err) => {
                    if (err) {
                        console.error('Error closing database:', err.message);
                        process.exit(1);
                    }
                    console.log('Database connection closed');
                    console.log('\nIndex creation complete!');
                    process.exit(0);
                });
            });
        });
    });
});
