const fs = require('fs');
const crypto = require('crypto');
const bodyParser = require('body-parser');
const express = require('express');
const http = require('http');
const path = require('path');
const sqlite3 = require('sqlite3').verbose();
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server);
const QRCode = require('qrcode');

const db = new sqlite3.Database('./data/db.sqlite');

// Criar tabela se não existir
db.run(`CREATE TABLE IF NOT EXISTS messages (
  room TEXT,
  message TEXT,
  timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)`);

// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'views/index.html'));
});

app.post('/create-room', (req, res) => {
    const roomCode = crypto.randomBytes(3).toString('hex').toUpperCase(); // Ex: 'A1B2C3'
    res.redirect(`/chat/${roomCode}`);
});

app.get('/chat/:roomId', async (req, res) => {
    const roomId = req.params.roomId;
    const chatFile = fs.readFileSync(path.join(__dirname, 'views/chat.html'), 'utf-8');
    const url = `${req.protocol}://${req.get('host')}/chat/${roomId}`;
    const qrDataURL = await QRCode.toDataURL(url);

    // Substitui o marcador especial <!--QR_CODE--> no HTML
    const finalPage = chatFile.replace('<!--QR_CODE-->', `<img src="${qrDataURL}" alt="QR Code da sala" class="qr-code">`);

    res.send(finalPage);
});

// WebSocket
io.on('connection', (socket) => {
    let roomId;

    socket.on('joinRoom', (room) => {
        roomId = room;

        const roomInfo = io.sockets.adapter.rooms.get(room) || new Set();
        const numUsers = roomInfo.size;

        if (numUsers >= 2) {
            socket.emit('roomFull');
            return;
        }

        socket.join(room);

        // Buscar mensagens anteriores
        db.all('SELECT message FROM messages WHERE room = ?', [room], (err, rows) => {
            if (rows) {
                rows.forEach(row => {
                    socket.emit('chatMessage', row.message);
                });
            }
        });
    });

    socket.on('chatMessage', (data) => {
        if (!roomId) return;

        io.to(roomId).emit('chatMessage', data);

        // Só salvar mensagens de texto no banco
        if (data.type === 'text') {
            db.run('INSERT INTO messages (room, message) VALUES (?, ?)', [roomId, data.content]);
        }
    });
});

const PORT = process.env.PORT || 3000;

// Autoapagar mensagens com mais de 7 dias
function apagarMensagensAntigas() {
    const seteDiasAtras = new Date();
    seteDiasAtras.setDate(seteDiasAtras.getDate() - 7);

    const dataLimite = seteDiasAtras.toISOString();

    db.run('DELETE FROM messages WHERE timestamp < ?', [dataLimite], function (err) {
        if (err) {
            console.error('Erro ao apagar mensagens antigas:', err);
        } else {
            console.log(`🧹 Mensagens com mais de 7 dias apagadas automaticamente.`);
        }
    });
}

// Executar a cada 24 horas (1000 * 60 * 60 * 24)
setInterval(apagarMensagensAntigas, 1000 * 60 * 60 * 24);

// Executar também ao iniciar o servidor
apagarMensagensAntigas();


server.listen(PORT, () => {
    console.log(`Servidor ativo: http://localhost:${PORT}`);
});
