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

dotenv.config();

const pool = new Pool({
    connectionString: process.env.DATABASE_URL || 'postgresql://postgres:password@db:5432/resistencia',
});

// Inicializar base de datos
export const initDb = async () => {
    const client = await pool.connect();
    try {
        await client.query(`
            CREATE TABLE IF NOT EXISTS game_logs (
                id SERIAL PRIMARY KEY,
                room_id UUID NOT NULL,
                room_name TEXT NOT NULL,
                host_name TEXT NOT NULL,
                players TEXT NOT NULL, -- Lista de nombres separada por comas
                max_players INTEGER NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                finished_at TIMESTAMP,
                winner TEXT, -- 'resistance' o 'spies'
                status TEXT DEFAULT 'active' -- 'active', 'finished', 'aborted'
            );
        `);
        console.log('[DB] Base de datos inicializada correctamente');
    } catch (err) {
        console.error('[DB] Error al inicializar base de datos:', err);
    } finally {
        client.release();
    }
};

// Registrar inicio de partida
export const logGameStart = async (roomId: string, roomName: string, hostName: string, maxPlayers: number) => {
    try {
        await pool.query(
            'INSERT INTO game_logs (room_id, room_name, host_name, players, max_players, status) VALUES ($1, $2, $3, $4, $5, $6)',
            [roomId, roomName, hostName, hostName, maxPlayers, 'active']
        );
    } catch (err) {
        console.error('[DB] Error al registrar inicio de partida:', err);
    }
};

// Actualizar lista de jugadores en tiempo real (opcional, pero útil para el histórico final)
export const updateGamePlayers = async (roomId: string, players: string[]) => {
    try {
        await pool.query(
            'UPDATE game_logs SET players = $1 WHERE room_id = $2 AND status = $3',
            [players.join(', '), roomId, 'active']
        );
    } catch (err) {
        console.error('[DB] Error al actualizar jugadores en log:', err);
    }
};

// Registrar fin de partida
export const logGameEnd = async (roomId: string, winner: string | null = null, aborted: boolean = false) => {
    try {
        await pool.query(
            'UPDATE game_logs SET finished_at = CURRENT_TIMESTAMP, winner = $1, status = $2 WHERE room_id = $3 AND status = $4',
            [winner, aborted ? 'aborted' : 'finished', roomId, 'active']
        );
    } catch (err) {
        console.error('[DB] Error al registrar fin de partida:', err);
    }
};

// Obtener historial
export const getGameHistory = async () => {
    try {
        const res = await pool.query('SELECT * FROM game_logs ORDER BY created_at DESC LIMIT 50');
        return res.rows;
    } catch (err) {
        console.error('[DB] Error al obtener historial:', err);
        return [];
    }
};

export default pool;
