const mysql = require('mysql2/promise');

const pool = mysql.createPool({
    host: process.env.DB_HOST || '192.168.1.6',
    user: process.env.DB_USER || 'bot',
    password: process.env.DB_PASSWORD || 'NxKr63LJB65pHv%t7E$JqgxKRsZMw%VIHEZAjq%^O0KYKjW#cRc^ebIH@%S9kaTh*GIg^D3ai4KBjMeXEh6xwv#9afQIR2$!2UB8C3ToXjnYFmzR%$lfpshnf8g@8229',
    database: process.env.DB_NAME || 'bot',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

async function initDB() {
    const conn = await pool.getConnection();
    try {
        // Tables de modération
        await conn.query(`
            CREATE TABLE IF NOT EXISTS bans (
                userId VARCHAR(32),
                guildId VARCHAR(32),
                reason TEXT,
                modId VARCHAR(32),
                timestamp BIGINT,
                type VARCHAR(20) NOT NULL,
                unbanDate BIGINT,
                PRIMARY KEY (userId, guildId)
            )
        `);

        await conn.query(`
            CREATE TABLE IF NOT EXISTS logs (
                id INT AUTO_INCREMENT PRIMARY KEY,
                userId VARCHAR(32),
                userTag VARCHAR(100),
                modId VARCHAR(32),
                modTag VARCHAR(100),
                action VARCHAR(50),
                reason TEXT,
                type ENUM('Permanent','Temporary') DEFAULT 'Permanent',
                guildId VARCHAR(32),
                timestamp BIGINT
            )
        `);

        await conn.query(`
            CREATE TABLE IF NOT EXISTS mutes (
                userId VARCHAR(32),
                guildId VARCHAR(32),
                reason TEXT,
                modId VARCHAR(32),
                modTag VARCHAR(100),
                timestamp BIGINT,
                unmuteDate BIGINT,
                type VARCHAR(20) NOT NULL,
                PRIMARY KEY (userId, guildId)
            )
        `);

        await conn.query(`
            CREATE TABLE IF NOT EXISTS staffbanmessages (
                userId VARCHAR(32) PRIMARY KEY,
                userTag VARCHAR(100),
                message TEXT,
                timestamp BIGINT
            )
        `);

        // Tables de tickets
        await conn.query(`
            CREATE TABLE IF NOT EXISTS tickets (
                id INT AUTO_INCREMENT PRIMARY KEY,
                ticketId VARCHAR(20) UNIQUE NOT NULL,
                channelId VARCHAR(32) UNIQUE NOT NULL,
                userId VARCHAR(32) NOT NULL,
                userTag VARCHAR(100),
                guildId VARCHAR(32) NOT NULL,
                type ENUM('Support', 'Plainte', 'Plainte Staff', 'Candidature', 'Problème Technique') NOT NULL,
                status ENUM('Ouvert', 'Fermé', 'En attente', 'Supprimé') DEFAULT 'Ouvert',
                createdAt BIGINT NOT NULL,
                closedAt BIGINT,
                closedBy VARCHAR(32),
                transcript TEXT,
                transcriptPath VARCHAR(255),
                claimedBy VARCHAR(32),
                claimedAt BIGINT,
                claimedByTag VARCHAR(100),
                INDEX idx_userId (userId),
                INDEX idx_guildId (guildId),
                INDEX idx_status (status),
                INDEX idx_claimedBy (claimedBy)
            )
        `);

        await conn.query(`
            CREATE TABLE IF NOT EXISTS ticket_messages (
                id INT AUTO_INCREMENT PRIMARY KEY,
                ticketId VARCHAR(20) NOT NULL,
                messageId VARCHAR(32) NOT NULL,
                userId VARCHAR(32) NOT NULL,
                userTag VARCHAR(100),
                content TEXT,
                attachments TEXT,
                timestamp BIGINT NOT NULL,
                INDEX idx_ticketId (ticketId),
                INDEX idx_messageId (messageId)
            )
        `);

        await conn.query(`
            CREATE TABLE IF NOT EXISTS candidature_responses (
                id INT AUTO_INCREMENT PRIMARY KEY,
                ticketId VARCHAR(20) NOT NULL,
                questionNumber INT NOT NULL,
                question TEXT NOT NULL,
                response TEXT,
                timestamp BIGINT NOT NULL,
                INDEX idx_ticketId (ticketId)
            )
        `);

        // Tables XP
        await conn.query(`
            CREATE TABLE IF NOT EXISTS user_xp (
                userId VARCHAR(32) NOT NULL,
                guildId VARCHAR(32) NOT NULL,
                xp INT DEFAULT 0,
                level INT DEFAULT 0,
                lastMessageTime BIGINT DEFAULT 0,
                totalMessages INT DEFAULT 0,
                totalVoiceTime INT DEFAULT 0,
                lastVoiceJoin BIGINT DEFAULT 0,
                lastBumpTime BIGINT DEFAULT 0,
                PRIMARY KEY (userId, guildId),
                INDEX idx_guildId (guildId),
                INDEX idx_xp (xp),
                INDEX idx_level (level)
            )
        `);

        await conn.query(`
            CREATE TABLE IF NOT EXISTS xp_excluded_channels (
                channelId VARCHAR(32) NOT NULL,
                guildId VARCHAR(32) NOT NULL,
                reason VARCHAR(255),
                addedBy VARCHAR(32),
                addedAt BIGINT,
                PRIMARY KEY (channelId, guildId),
                INDEX idx_guildId (guildId)
            )
        `);

        await conn.query(`
            CREATE TABLE IF NOT EXISTS xp_logs (
                id INT AUTO_INCREMENT PRIMARY KEY,
                userId VARCHAR(32) NOT NULL,
                guildId VARCHAR(32) NOT NULL,
                xpGained INT NOT NULL,
                source VARCHAR(50) NOT NULL,
                multiplier DECIMAL(3,2) DEFAULT 1.00,
                timestamp BIGINT NOT NULL,
                INDEX idx_userId (userId),
                INDEX idx_guildId (guildId),
                INDEX idx_timestamp (timestamp)
            )
        `);

        // Tables Bump
        await conn.query(`
            CREATE TABLE IF NOT EXISTS bumps (
                id INT AUTO_INCREMENT PRIMARY KEY,
                userId VARCHAR(32) NOT NULL,
                guildId VARCHAR(32) NOT NULL,
                bumpTime BIGINT NOT NULL,
                reminderSent BOOLEAN DEFAULT FALSE,
                INDEX idx_userId (userId),
                INDEX idx_guildId (guildId),
                INDEX idx_bumpTime (bumpTime)
            )
        `);

        await conn.query(`
            CREATE TABLE IF NOT EXISTS bump_channels (
                channelId VARCHAR(32) NOT NULL,
                guildId VARCHAR(32) NOT NULL,
                bumpBotId VARCHAR(32),
                addedBy VARCHAR(32),
                addedAt BIGINT,
                PRIMARY KEY (channelId, guildId),
                INDEX idx_guildId (guildId)
            )
        `);

        // Tables Profils
        await conn.query(`
            CREATE TABLE IF NOT EXISTS user_profiles (
                userId VARCHAR(32) NOT NULL,
                guildId VARCHAR(32) NOT NULL,
                signature TEXT,
                birthday DATE,
                color VARCHAR(7),
                gender VARCHAR(50),
                location VARCHAR(100),
                updatedAt BIGINT,
                PRIMARY KEY (userId, guildId),
                INDEX idx_guildId (guildId)
            )
        `);

        // Migrations (pour compatibilité existante)
        // On utilise la syntaxe standard sans IF NOT EXISTS pour compatibilité maximale
        try { 
            await conn.query('ALTER TABLE bans ADD COLUMN guildId VARCHAR(32)'); 
            await conn.query('ALTER TABLE bans DROP PRIMARY KEY');
            await conn.query('ALTER TABLE bans ADD PRIMARY KEY (userId, guildId)');
        } catch {}
        
        try { await conn.query('ALTER TABLE logs ADD COLUMN guildId VARCHAR(32)'); } catch {}
        try { await conn.query('ALTER TABLE logs MODIFY COLUMN action VARCHAR(50)'); } catch {}
        try { await conn.query('ALTER TABLE tickets ADD COLUMN transcriptPath VARCHAR(255)'); } catch {}
        try { await conn.query('ALTER TABLE tickets ADD COLUMN claimedBy VARCHAR(32)'); } catch {}
        try { await conn.query('ALTER TABLE tickets ADD COLUMN claimedAt BIGINT'); } catch {}
        try { await conn.query('ALTER TABLE tickets ADD COLUMN claimedByTag VARCHAR(100)'); } catch {}
        
        // Migrations Profils (Sans IF NOT EXISTS)
        try { await conn.query('ALTER TABLE user_profiles ADD COLUMN color VARCHAR(7)'); } catch {}
        try { await conn.query('ALTER TABLE user_profiles ADD COLUMN gender VARCHAR(50)'); } catch {}
        try { await conn.query('ALTER TABLE user_profiles ADD COLUMN location VARCHAR(100)'); } catch {}

    } finally {
        conn.release();
    }
}

initDB().catch(console.error);

module.exports = pool;