/**
 * Serveur web pour héberger les transcripts avec authentification Discord
 * Interface professionnelle avec dashboard et statistiques
 */

require('dotenv').config();
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const db = require('../functions/database/db.js');

// --- DEBUG: Fonction pour afficher l'arborescence ---
function printTree(dir, prefix = '') {
    if (!fs.existsSync(dir)) return console.log(`${prefix}❌ ${dir} (Introuvable)`);
    console.log(`${prefix}📁 ${path.basename(dir)}/`);
    try {
        const files = fs.readdirSync(dir);
        files.forEach(file => {
            const fullPath = path.join(dir, file);
            const isDir = fs.statSync(fullPath).isDirectory();
            if (isDir) {
                printTree(fullPath, prefix + '  ');
            } else {
                console.log(`${prefix}  📄 ${file}`);
            }
        });
    } catch (e) {
        console.log(`${prefix}  ❌ Erreur lecture: ${e.message}`);
    }
}

let DiscordStrategy;
try {
    DiscordStrategy = require('passport-discord').Strategy;
} catch (err) {
    console.warn('⚠️  passport-discord non installé.');
    DiscordStrategy = null;
}

const app = express();
const PORT = process.env.TRANSCRIPT_PORT || 3000;

// --- CUSTOM HEADER (La petite touche perso) ---
app.use((req, res, next) => {
    res.setHeader('X-Powered-By', 'Femboy Croissant WebEngine');
    next();
});

// --- DEBUG: Middleware de log HTTP ---
app.use((req, res, next) => {
    if (!req.url.includes('.css') && !req.url.includes('.js') && !req.url.includes('.png')) {
        console.log(`[HTTP] ${req.method} ${req.url}`);
    }
    next();
});

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(session({
    secret: process.env.SESSION_SECRET || 'change-me-in-production',
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: process.env.NODE_ENV === 'production',
        httpOnly: true,
        maxAge: 24 * 60 * 60 * 1000
    }
}));

app.use(passport.initialize());
app.use(passport.session());

let discordStrategyConfigured = false;
const discordClientId = process.env.DISCORD_CLIENT_ID || process.env.CLIENT_ID;
const discordClientSecret = process.env.DISCORD_CLIENT_SECRET || process.env.CLIENT_SECRET;

if (DiscordStrategy && discordClientId && discordClientSecret) {
    try {
        passport.use('discord', new DiscordStrategy({
            clientID: discordClientId,
            clientSecret: discordClientSecret,
            callbackURL: process.env.DISCORD_CALLBACK_URL || `http://localhost:${PORT}/auth/discord/callback`,
            scope: ['identify', 'guilds']
        }, (accessToken, refreshToken, profile, done) => {
            return done(null, profile);
        }));
        discordStrategyConfigured = true;
        console.log('✅ Stratégie Discord OAuth configurée avec succès');
    } catch (err) {
        console.error('❌ Erreur config Discord:', err);
        discordStrategyConfigured = false;
    }
}

passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((obj, done) => done(null, obj));

function isAuthenticated(req, res, next) {
    if (req.isAuthenticated()) return next();
    res.redirect('/login');
}

function isModerator(user) {
    const moderatorIds = process.env.MODERATOR_IDS ? process.env.MODERATOR_IDS.split(',') : [];
    return moderatorIds.includes(user.id);
}

async function hasPermission(req, res, next) {
    if (!req.isAuthenticated()) return res.redirect('/login');

    const filePath = req.params[0];
    if (filePath.endsWith('.css')) return next();

    try {
        const [tickets] = await db.query(
            'SELECT * FROM tickets WHERE transcriptPath = ? OR transcriptPath = ? OR transcriptPath LIKE ?',
            [filePath, `transcripts/${filePath}`, `%${filePath}`]
        );

        if (tickets.length === 0) return res.status(404).send('Transcript introuvable.');

        const ticket = tickets[0];
        const userId = req.user.id;

        if (ticket.userId === userId) return next();
        if (isModerator(req.user)) return next();

        return res.status(403).send('Accès refusé.');

    } catch (err) {
        console.error('Erreur permissions:', err);
        return res.status(500).send('Erreur serveur.');
    }
}

// --- HEAD COMMUN (Lien vers style.css) ---
const COMMON_HEAD = `
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/static/style.css">
`;

function generateDashboardHTML(user, stats, userTickets, allTickets, isMod) {
    let userAvatar;
    if (user.avatar) userAvatar = `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=128`;
    else if (user.discriminator && user.discriminator !== '0') userAvatar = `https://cdn.discordapp.com/embed/avatars/${user.discriminator % 5}.png`;
    else userAvatar = `https://cdn.discordapp.com/embed/avatars/${parseInt(user.id) % 5}.png`;

    const statsHTML = isMod ? `
        <div class="stats-grid">
            <div class="stat-card"><div class="stat-icon icon-blue"><i class="fa-solid fa-ticket"></i></div><div class="stat-info"><h3>Total Tickets</h3><p>${stats.totalTickets}</p></div></div>
            <div class="stat-card"><div class="stat-icon icon-green"><i class="fa-solid fa-folder-open"></i></div><div class="stat-info"><h3>Ouverts</h3><p>${stats.openTickets}</p></div></div>
            <div class="stat-card"><div class="stat-icon icon-red"><i class="fa-solid fa-box-archive"></i></div><div class="stat-info"><h3>Fermés</h3><p>${stats.closedTickets}</p></div></div>
            <div class="stat-card"><div class="stat-icon icon-orange"><i class="fa-solid fa-user-tag"></i></div><div class="stat-info"><h3>Mes Tickets (Gérés)</h3><p>${stats.myTickets}</p></div></div>
        </div>
    ` : '';

    const allTicketsHTML = isMod ? `
        <div class="section">
            <h2 class="section-title">🌐 Tous les Transcripts</h2>
            ${allTickets.length > 0 ? `<div class="tickets-grid">${allTickets.slice(0, 6).map(ticket => generateTicketCard(ticket)).join('')}</div>${allTickets.length > 6 ? `<p style="text-align: center; margin-top: 20px;"><a href="/transcripts" class="view-btn">Voir tous (${allTickets.length})</a></p>` : ''}` : '<div class="no-tickets">Aucun transcript disponible.</div>'}
        </div>
    ` : '';

    const myTicketsTitle = isMod ? "📄 Mes Tickets (Gérés)" : "📄 Mes Tickets (Créés)";

    return `<!DOCTYPE html>
<html lang="fr">
<head>
    <title>Dashboard • Femboy Croissant</title>
    ${COMMON_HEAD}
</head>
<body>
    <nav class="navbar">
        <a href="/" class="brand"><i class="fa-solid fa-croissant"></i> Femboy Croissant</a>
        <div class="nav-links">
            <a href="/" class="nav-link active">Dashboard</a>
            ${isMod ? '<a href="/transcripts" class="nav-link">Tous les Transcripts</a>' : ''}
        </div>
        <div class="user-menu">
            <img src="${userAvatar}" class="avatar" alt="Avatar">
            <a href="/auth/logout" class="logout"><i class="fa-solid fa-right-from-bracket"></i></a>
        </div>
    </nav>

    <div class="container">
        <div class="section-header">
            <h1 class="title">Vue d'ensemble</h1>
            <span style="color: var(--text-secondary)">Bienvenue, ${escapeHtml(user.username)}</span>
        </div>

        ${statsHTML}

        <div class="section">
            <h2 class="section-title">${myTicketsTitle}</h2>
            ${userTickets.length > 0 ? `<div class="tickets-grid">${userTickets.map(ticket => generateTicketCard(ticket)).join('')}</div>` : '<div class="no-tickets">Aucun ticket trouvé.</div>'}
        </div>

        ${allTicketsHTML}
    </div>
</body>
</html>`;
}

function generateTranscriptsPageHTML(user, tickets) {
    const userAvatar = user.avatar 
        ? `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png` 
        : `https://cdn.discordapp.com/embed/avatars/${parseInt(user.id) % 5}.png`;

    return `<!DOCTYPE html>
<html lang="fr">
<head>
    <title>Transcripts • Femboy Croissant</title>
    ${COMMON_HEAD}
    <script>
        function filterTable(type) {
            const rows = document.querySelectorAll('tbody tr');
            const buttons = document.querySelectorAll('.filter-btn');
            buttons.forEach(btn => btn.classList.remove('active'));
            document.querySelector(\`button[onclick="filterTable('\${type}')"]\`).classList.add('active');
            rows.forEach(row => {
                const rowType = row.getAttribute('data-type');
                if (type === 'all' || rowType === type) row.style.display = '';
                else row.style.display = 'none';
            });
        }
    </script>
</head>
<body>
    <nav class="navbar">
        <a href="/" class="brand"><i class="fa-solid fa-croissant"></i> Femboy Croissant</a>
        <div class="nav-links">
            <a href="/" class="nav-link">Dashboard</a>
            <a href="/transcripts" class="nav-link active">Tous les Transcripts</a>
        </div>
        <div class="user-menu">
            <img src="${userAvatar}" class="avatar" alt="Avatar">
            <a href="/auth/logout" class="logout"><i class="fa-solid fa-right-from-bracket"></i></a>
        </div>
    </nav>

    <div class="container">
        <div class="section-header">
            <h1 class="title">Archives des Tickets</h1>
            <div class="filters">
                <button class="filter-btn active" onclick="filterTable('all')">Tout</button>
                <button class="filter-btn" onclick="filterTable('Support')">Support</button>
                <button class="filter-btn" onclick="filterTable('Plainte')">Plainte</button>
                <button class="filter-btn" onclick="filterTable('Candidature')">Candidature</button>
                <button class="filter-btn" onclick="filterTable('Problème Technique')">Technique</button>
            </div>
        </div>

        <div class="card">
            ${tickets.length > 0 ? `
                <div class="table-responsive">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Type</th>
                                <th>Créateur</th>
                                <th>Géré par</th>
                                <th>Date</th>
                                <th>Statut</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${tickets.map(t => generateTableRow(t, true)).join('')}
                        </tbody>
                    </table>
                </div>
            ` : `
                <div class="empty-state">
                    <div class="empty-icon"><i class="fa-solid fa-box-open"></i></div>
                    <p>Aucun transcript disponible.</p>
                </div>
            `}
        </div>
    </div>
</body>
</html>`;
}

function generateTableRow(ticket, showModerator = false) {
    const date = new Date(ticket.createdAt).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
    
    let url = ticket.transcriptPath || '#';
    if (url !== '#' && !url.startsWith('transcripts/') && !url.startsWith('/transcripts/')) {
        url = `/transcripts/${url}`;
    } else if (url !== '#' && !url.startsWith('/')) {
        url = `/${url}`;
    }

    const statusClass = `status-${ticket.status.toLowerCase().replace(' ', '-')}`;
    
    let modCell = '';
    if (showModerator) {
        const mod = ticket.claimedByTag ? escapeHtml(ticket.claimedByTag) : (ticket.claimedBy ? 'Modérateur' : '-');
        modCell = `<td><span style="color: var(--text-secondary)">${mod}</span></td>`;
    }

    return `
        <tr data-type="${ticket.type}">
            <td style="font-family: monospace; color: var(--accent);">${ticket.ticketId}</td>
            <td><span class="badge type-badge">${ticket.type}</span></td>
            <td><strong>${escapeHtml(ticket.userTag)}</strong></td>
            ${modCell}
            <td style="color: var(--text-secondary)">${date}</td>
            <td><span class="badge ${statusClass}"><span class="badge-dot"></span>${ticket.status}</span></td>
            <td>
                ${ticket.transcriptPath ? 
                    `<a href="${url}" class="btn btn-primary" target="_blank"><i class="fa-solid fa-eye"></i> Voir</a>` : 
                    `<span class="btn btn-ghost" style="cursor: not-allowed; opacity: 0.5"><i class="fa-solid fa-ban"></i></span>`
                }
            </td>
        </tr>
    `;
}

function generateTicketCard(ticket) {
    const date = formatDate(ticket.createdAt);
    
    let url = ticket.transcriptPath || '#';
    if (url !== '#' && !url.startsWith('transcripts/') && !url.startsWith('/transcripts/')) {
        url = `/transcripts/${url}`;
    } else if (url !== '#' && !url.startsWith('/')) {
        url = `/${url}`;
    }

    const typeEmojis = { 'Support': '💬', 'Plainte': '📢', 'Plainte Staff': '⚠️', 'Candidature': '📝', 'Problème Technique': '🔧' };

    return `
        <div class="ticket-card">
            <div class="ticket-header">
                <div class="ticket-id">${typeEmojis[ticket.type] || '🎫'} ${ticket.ticketId}</div>
                <span class="ticket-type">${ticket.type}</span>
            </div>
            <div class="ticket-info">
                <div><strong>Créé par:</strong> ${escapeHtml(ticket.userTag)}</div>
                ${ticket.claimedBy ? `<div><strong>Géré par:</strong> ${ticket.claimedByTag || 'Modérateur'}</div>` : ''}
                <div><strong>Date:</strong> ${date}</div>
            </div>
            <div><span class="ticket-status">${ticket.status}</span></div>
            ${ticket.transcriptPath ? `<a href="${url}" class="view-btn">Voir le transcript</a>` : '<span style="color: #999;">Transcript non disponible</span>'}
        </div>
    `;
}

function formatDate(timestamp) {
    try {
        return new Intl.DateTimeFormat('fr-FR', {
            timeZone: 'Europe/Paris', year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit'
        }).format(new Date(timestamp));
    } catch { return new Date(timestamp).toLocaleString(); }
}

function escapeHtml(text) {
    if (!text) return '';
    return text.replace(/[&<>"']/g, m => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' })[m]);
}

// Routes
app.get('/login', (req, res) => {
    res.send(`<!DOCTYPE html>
    <html>
    <head>
        <title>Connexion</title>
        ${COMMON_HEAD}
        <style>body { display: flex; align-items: center; justify-content: center; }</style>
    </head>
    <body>
        <div class="card" style="padding: 3rem; text-align: center; max-width: 400px;">
            <h1 style="margin-bottom: 1rem;">🔐 Accès Restreint</h1>
            <p style="color: var(--text-secondary); margin-bottom: 2rem;">Veuillez vous connecter avec votre compte Discord pour accéder aux archives.</p>
            <a href="/auth/discord" class="btn btn-primary" style="width: 100%; justify-content: center; padding: 1rem;">
                <i class="fa-brands fa-discord"></i> Se connecter avec Discord
            </a>
        </div>
    </body>
    </html>`);
});

app.get('/auth/discord', (req, res, next) => {
    if (!discordStrategyConfigured) return res.send('Erreur configuration OAuth');
    passport.authenticate('discord')(req, res, next);
});

app.get('/auth/discord/callback',
    (req, res, next) => {
        if (!discordStrategyConfigured) return res.redirect('/login?error=not_configured');
        passport.authenticate('discord', { failureRedirect: '/login?error=auth_failed' })(req, res, next);
    },
    (req, res) => res.redirect('/')
);

app.get('/auth/logout', (req, res) => {
    req.logout(() => res.redirect('/login'));
});

app.use('/static', express.static(path.join(__dirname, 'public')));

// --- FIX CSS: Route explicite avec Header ---
app.get('*/transcript.css', (req, res) => {
    res.setHeader('Content-Type', 'text/css');
    res.sendFile(path.join(process.cwd(), 'transcripts', 'transcript.css'));
});

app.get(['/tickets/*', '/transcripts/*'], isAuthenticated, hasPermission, (req, res) => {
    const filePath = req.params[0];
    const fullPath = path.join(process.cwd(), 'transcripts', filePath);
    if (!fs.existsSync(fullPath)) return res.status(404).send('Transcript introuvable.');
    res.sendFile(fullPath);
});

app.get('/', isAuthenticated, async (req, res) => {
    try {
        const userId = req.user.id;
        const isMod = isModerator(req.user);

        let stats = {};
        let userTickets = [];
        let allTickets = [];

        if (isMod) {
            const [totalStats] = await db.query('SELECT COUNT(*) as total FROM tickets');
            const [myTicketsStats] = await db.query('SELECT COUNT(*) as total FROM tickets WHERE claimedBy = ?', [userId]);
            const [openStats] = await db.query('SELECT COUNT(*) as total FROM tickets WHERE status = ?', ['Ouvert']);
            const [closedStats] = await db.query('SELECT COUNT(*) as total FROM tickets WHERE status = ?', ['Fermé']);

            stats = {
                totalTickets: totalStats[0].total,
                myTickets: myTicketsStats[0].total,
                openTickets: openStats[0].total,
                closedTickets: closedStats[0].total
            };

            [userTickets] = await db.query('SELECT * FROM tickets WHERE claimedBy = ? AND transcriptPath IS NOT NULL ORDER BY createdAt DESC LIMIT 10', [userId]);
            [allTickets] = await db.query('SELECT * FROM tickets WHERE transcriptPath IS NOT NULL ORDER BY createdAt DESC LIMIT 10', []);
        } else {
            [userTickets] = await db.query('SELECT * FROM tickets WHERE userId = ? AND transcriptPath IS NOT NULL ORDER BY createdAt DESC LIMIT 20', [userId]);
        }

        res.send(generateDashboardHTML(req.user, stats, userTickets, allTickets, isMod));
    } catch (err) {
        console.error('Erreur dashboard:', err);
        res.status(500).send('Erreur serveur.');
    }
});

app.get('/transcripts', isAuthenticated, async (req, res) => {
    if (!isModerator(req.user)) return res.status(403).send('Accès refusé.');

    try {
        const [allTickets] = await db.query('SELECT * FROM tickets WHERE transcriptPath IS NOT NULL ORDER BY createdAt DESC', []);
        res.send(generateTranscriptsPageHTML(req.user, allTickets));
    } catch (err) {
        console.error('Erreur transcripts:', err);
        res.status(500).send('Erreur serveur.');
    }
});

app.listen(PORT, () => {
    console.log(`🌐 Serveur de transcripts démarré sur le port ${PORT}`);
    console.log('--- STRUCTURE DES FICHIERS ---');
    printTree(path.join(__dirname, 'public'), 'server/public');
    printTree(path.join(process.cwd(), 'transcripts'), 'transcripts');
    console.log('------------------------------');
});