const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const db = require('./config/database');
require('dotenv').config();

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

// Middleware
app.use(cors({ origin: process.env.CORS_ORIGIN || '*' }));
if (process.env.NODE_ENV !== 'production') {
    app.use((req, res, next) => {
        res.setHeader(
            'Content-Security-Policy',
            "default-src 'self' blob: data:; " +
            "script-src 'self' 'unsafe-inline' 'unsafe-eval'; " +
            "style-src 'self' 'unsafe-inline'; " +
            "img-src 'self' data: blob:; " +
            "font-src 'self' data:; " +
            "connect-src 'self' http://localhost:* ws://localhost:* http://127.0.0.1:* ws://127.0.0.1:*;"
        );
        next();
    });
}
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Routes (Placeholder)
app.get('/api/health', (req, res) => {
    res.json({ status: 'OK', timestamp: new Date() });
});

// Import Routes
const clientesRouter = require('./routes/clientes');
const cuentasRouter = require('./routes/cuentas');
const ordenesRouter = require('./routes/ordenes');
const transaccionesRouter = require('./routes/transacciones');
const notasRouter = require('./routes/notas');
const mensajesRouter = require('./routes/mensajes');
const dashboardRouter = require('./routes/dashboard');
const importRouter = require('./routes/import');
const authRouter = require('./routes/auth');
const usuariosRouter = require('./routes/usuarios');
const programasRouter = require('./routes/programas');
const contactosRouter = require('./routes/contactos');
const catalogosRouter = require('./routes/catalogos');
const referralsRouter = require('./routes/referrals');
const programasVisitaRouter = require('./routes/programas_visita');
const asesoresRouter = require('./routes/asesores');

app.use('/api/clientes', clientesRouter);
app.use('/api/cuentas', cuentasRouter);
app.use('/api/ordenes', ordenesRouter);
app.use('/api/transacciones', transaccionesRouter);
app.use('/api/notas', notasRouter);
app.use('/api/mensajes', mensajesRouter);
app.use('/api/dashboard', dashboardRouter);
app.use('/api/import', importRouter);
app.use('/api/auth', authRouter);
app.use('/api/usuarios', usuariosRouter);
app.use('/api/users', usuariosRouter);
app.use('/api/programas', programasRouter);
app.use('/api/contactos', contactosRouter);
app.use('/api/contacts', contactosRouter);
app.use('/api/catalogos', catalogosRouter);
app.use('/api/referrals', referralsRouter);
app.use('/api/programs', programasVisitaRouter);
app.use('/api/asesores', asesoresRouter);

const oportunidadesRoutes = require('./routes/oportunidades');
const pipelineRoutes = require('./routes/pipeline');
const origenesRoutes = require('./routes/origenes');

app.use('/api/oportunidades', oportunidadesRoutes);
app.use('/api/opportunities', oportunidadesRoutes);
app.use('/api/pipeline', pipelineRoutes);
app.use('/api/origenes', origenesRoutes);

// Serve static files from data (for images if needed)
app.use('/data', express.static(path.join(__dirname, '../data')));

const distPath = path.join(__dirname, '../../frontend/dist');
if (fs.existsSync(distPath)) {
    app.use(express.static(distPath));
    app.get('*', (req, res, next) => {
        if (req.path.startsWith('/api')) return next();
        res.sendFile(path.join(distPath, 'index.html'));
    });
}

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
    console.log(`Environment: ${process.env.NODE_ENV}`);
    console.log(`Database: ${process.env.DB_PATH}`);
});
