import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';
import helmet from 'helmet';
import compression from 'compression';
import { apiLimiter } from './server/middlewares/rateLimiters.js';
import { runStartupMigrations } from './server/config/migrate.js';

// Import Routes
import authRoutes from './server/routes/authRoutes.js';
import systemRoutes from './server/routes/systemRoutes.js';
import rpcRoutes from './server/routes/rpcRoutes.js';
import uploadRoutes from './server/routes/uploadRoutes.js';
import orderRoutes from './server/routes/orderRoutes.js';
import crudRoutes from './server/routes/crudRoutes.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

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

// Security & Proxies
app.set('trust proxy', 1);
app.use(helmet({ contentSecurityPolicy: false }));
app.use(compression());
app.use(cors({
    origin: process.env.ALLOWED_ORIGIN || '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
    allowedHeaders: ['Content-Type', 'Authorization'],
}));
app.use(express.json({ limit: '10mb' }));

// Logging
app.use((req, res, next) => {
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
    next();
});

// Rate Limiter
app.use('/api/', apiLimiter);

// Bind Controllers/Routes
app.use('/api/auth', authRoutes);
app.use('/api/materials', express.static(path.join(__dirname, 'public', 'materials')));
app.use('/api/', systemRoutes);
app.use('/api/rpc', rpcRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/', crudRoutes); // Place crudRoutes last as it uses '/*' wildcard matcher

// Serve React Frontend
app.use(express.static(path.join(__dirname, 'public')));
app.get('*', (req, res) => {
    if (req.url.startsWith('/api')) {
        return res.status(404).json({ message: 'API Route Not Found' });
    }
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.listen(port, async () => {
    // Run Database Safe Migrations Let 
    await runStartupMigrations();
    
    console.log(`🚀 Unified Backend serving React from 'public/' running on port ${port}`);
    console.log(`📂 Database: ${process.env.DB_NAME} on ${process.env.DB_HOST}`);
    console.log(`🔗 Health Check: http://localhost:${port}/api/health`);
    console.log(`📊 DB Summary: http://localhost:${port}/api/debug/db-summary`);
});
