const db = require('./analytics-db');

/**
 * Rooms Database Module
 * Handles room management for multiplayer games
 */
class RoomsDB {
    constructor() {
        // Create table first (before preparing statements)
        db.exec(`
            CREATE TABLE IF NOT EXISTS rooms (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                game_type TEXT NOT NULL,
                name TEXT NOT NULL,
                password TEXT,
                type TEXT NOT NULL DEFAULT 'public',
                status TEXT DEFAULT 'active',
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL
            )
        `);

        // Now prepare statements (table exists)
        this.statements = {
            insert: db.prepare(`
                INSERT INTO rooms (game_type, name, password, type, status, created_at, updated_at)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            `),
            update: db.prepare(`
                UPDATE rooms 
                SET name = ?, password = ?, type = ?, status = ?, updated_at = ?
                WHERE id = ?
            `),
            delete: db.prepare('DELETE FROM rooms WHERE id = ?'),
            getAll: db.prepare('SELECT * FROM rooms ORDER BY game_type, name'),
            getByGame: db.prepare('SELECT * FROM rooms WHERE game_type = ? ORDER BY name'),
            getActiveByGame: db.prepare("SELECT * FROM rooms WHERE game_type = ? AND status = 'active' ORDER BY name"),
            getById: db.prepare('SELECT * FROM rooms WHERE id = ?'),
            count: db.prepare('SELECT COUNT(*) as count FROM rooms')
        };
    }

    /**
     * Get all rooms
     */
    getAllRooms() {
        return this.statements.getAll.all();
    }

    /**
     * Get rooms by game type
     */
    getRoomsByGame(gameType) {
        return this.statements.getByGame.all(gameType);
    }

    /**
     * Get active rooms by game type
     */
    getActiveRoomsByGame(gameType) {
        return this.statements.getActiveByGame.all(gameType);
    }

    /**
     * Get room by ID
     */
    getById(id) {
        return this.statements.getById.get(id);
    }

    /**
     * Create a new room
     */
    createRoom(gameType, name, password, type, status = 'active') {
        const now = new Date().toISOString();
        return this.statements.insert.run(gameType, name, password, type, status, now, now);
    }

    /**
     * Update a room
     */
    updateRoom(id, name, password, type, status) {
        const now = new Date().toISOString();
        return this.statements.update.run(name, password, type, status, now, id);
    }

    /**
     * Delete a room
     */
    deleteRoom(id) {
        return this.statements.delete.run(id);
    }
}

module.exports = new RoomsDB();
