// Relovable API v3.5 — boot (nodemon trigger)
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const helmet = require('helmet');

const { router: licenseRoutes } = require('./src/routes/license');
const adminRoutes = require('./src/routes/admin');
const authRoutes = require('./src/routes/auth');
const versionRoutes = require('./src/routes/version');
const adminUpdatesRoutes = require('./src/routes/admin-updates');
const lovableRoutes = require('./src/routes/lovable');
const syncRoutes = require('./src/routes/sync');
const monitoringRoutes = require('./src/routes/monitoring');
const broadcastRoutes = require('./src/routes/broadcast');
const promptRoutes = require('./src/routes/prompts');

const db = require('./src/db');

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

app.use(helmet({
    contentSecurityPolicy: {
        directives: {
            defaultSrc: ["*"],
            scriptSrc: ["*", "'unsafe-inline'", "'unsafe-eval'"],
            scriptSrcElem: ["*", "'unsafe-inline'"],
            scriptSrcAttr: ["'unsafe-inline'"],
            styleSrc: ["*", "'unsafe-inline'"],
            imgSrc: ["*", "data:", "blob:"],
            connectSrc: ["*"]
        }
    },
    crossOriginEmbedderPolicy: false,
}));

app.use(cors());
app.use(express.json({ limit: '50mb' }));

// Global Logger for Debugging
app.use((req, res, next) => {
    console.log(`[REQ] ${new Date().toISOString()} | ${req.method} ${req.url}`);
    next();
});

// Public Test Route (To verify 404s)
app.get('/api/test-debug', (req, res) => {
    res.json({ message: 'API /api/ prefix is working!', timestamp: new Date() });
});

// Static
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', express.static(path.join(__dirname, '../relovable-admin/dist')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// ── API ROUTES ─────────────────────────────────────────────────────────────

// 1. Admin Specific (Must come before generic /api)
app.use('/api/admin', authRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/admin', adminUpdatesRoutes);
app.use('/api/admin', broadcastRoutes);
app.use('/api/admin', promptRoutes);
app.use('/api/admin/monitoring', monitoringRoutes);

// 2. Extension / Lovable V1
app.use('/api/v1/lovable', broadcastRoutes);
app.use('/api/v1/lovable', promptRoutes);
app.use('/api/v1/lovable', lovableRoutes);
app.use('/api/v1/lovable', syncRoutes);
app.use('/api/monitor', monitoringRoutes);

// 3. Generic/Legacy Extension Routes (Last, since prefix is just /api)
app.use('/api', licenseRoutes);
app.use('/api', versionRoutes);

// ── HEALTH & UTILS ──────────────────────────────────────────────────────────


// ── HEALTH & UTILS ──────────────────────────────────────────────────────────

// Root route for cPanel/Passenger health checks
app.get('/', (req, res) => {
    res.setHeader('Content-Type', 'text/html; charset=UTF-8');
    res.send(`
        <!DOCTYPE html>
        <html>
            <head><title>Relovable API</title></head>
            <body style="font-family: sans-serif; background: #0a0a14; color: #fff; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0;">
                <div style="text-align: center; border: 1px solid #ffffff10; padding: 2rem; border-radius: 1rem; background: #ffffff05;">
                    <h1 style="color: #a78bfa;">Relovable API v3.5</h1>
                    <p style="color: #64748b;">Status: <span style="color: #4ade80;">ONLINE</span></p>
                    <hr style="border: 0; border-top: 1px solid #ffffff10; margin: 1.5rem 0;">
                    <small style="color: #475569;">Production environment (Phusion Passenger)</small>
                </div>
            </body>
        </html>
    `);
});

app.get('/health', (req, res) => {
    res.json({ status: 'ok', version: '3.5.0', timestamp: new Date().toISOString() });
});

// React SPA fallback for /admin routes
app.get('/admin/*', (req, res) => {
    res.sendFile(path.join(__dirname, '../relovable-admin/dist/index.html'));
});

// ── Erro Global ──────────────────────────────────────────────────────────────
app.use((err, req, res, next) => {
    console.error('[GLOBAL ERROR]', err);
    res.status(500).json({
        error: err.message,
        stack: err.stack
    });
});

app.use((req, res) => {
    console.log(`[404] ${req.method} ${req.path}`);
    res.status(404).json({ error: 'Endpoint não encontrado', path: req.path });
});

// ── Database Initialization ─────────────────────────────────────────────
const isProd = process.env.NODE_ENV === 'production';

async function boot() {
    console.log(`[BOOT] Inicializando em modo: ${process.env.NODE_ENV || 'development'}`);

    try {
        if (isProd) {
            console.log('[DB] Verificando conexão MySQL...');
            const conn = await db.getConnection();
            console.log('✅ Conexão MySQL OK.');
            conn.release();
        } else {
            await db.initDB();
        }
    } catch (err) {
        console.error('❌ ERRO NA CONEXÃO COM BANCO:', err.message);
        console.log('⚠️ O servidor continuará rodando, mas endpoints de API podem falhar até que o banco esteja OK.');
    }

    const server = app.listen(PORT, () => {
        const addr = server.address();
        const bind = typeof addr === 'string' ? addr : 'port ' + addr.port;
        console.log('');
        console.log('🚀 ================================');
        console.log('   WorkBestGames — Relovable API v3.5');
        console.log('   Status:    ONLINE');
        console.log(`   Listening: ${bind}`);
        console.log('🚀 ================================');
        console.log('');
    });

    server.on('error', (e) => {
        if (e.code === 'EADDRINUSE') {
            console.error(`❌ Porta ${PORT} em uso.`);
        } else {
            console.error('❌ Erro no servidor:', e);
        }
        process.exit(1);
    });
}

// Inicia o boot
boot();

// Exporta para o Passenger no cPanel (importante!)
module.exports = app;
