const express = require('express');
const cors = require('cors');
const path = require('path');

const connectDB = require('./config/db');
const authRoutes = require('./routes/authRoutes');
const apiRoutes = require('./routes/apiRoutes');

// Khởi động Image Processing Worker
require('./routes/imageWorker');

// Connect to Database
connectDB();

const app = express();

// Standard middlewares
const corsOptions = {
    origin: function (origin, callback) {
        // Cho phép các request không có origin (như Postman hoặc khi render phía server)
        if (!origin) return callback(null, true);
        
        const systemHost = process.env.SYSTEM_HOST || 'http://localhost:5000';
        let allowedOrigin;
        try {
            allowedOrigin = new URL(systemHost).origin;
        } catch (e) {
            allowedOrigin = systemHost;
        }

        // Trong môi trường dev, cho phép localhost với bất kỳ port nào
        const isLocal = origin.includes('localhost') || origin.includes('127.0.0.1') || origin.includes('::1');
        if (process.env.NODE_ENV !== 'production' && isLocal) {
            return callback(null, true);
        }

        if (origin === allowedOrigin) return callback(null, true);
        
        console.warn(`[CORS Blocked]: Origin ${origin} is not allowed by configuration.`);
        callback(new Error('Not allowed by CORS'));
    },
    credentials: true,
    maxAge: 86400 // Cho phép trình duyệt cache kết quả preflight OPTIONS trong 24 giờ
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Request Logger Middleware
app.use((req, res, next) => {
    const start = Date.now();
    res.on('finish', () => {
        const duration = Date.now() - start;
        console.log(`[${new Date().toISOString()}] ${req.method} ${req.originalUrl} - ${res.statusCode} (${duration}ms)`);
    });
    next();
});

// API Routes
app.use('/api/auth', authRoutes);
app.use('/api', apiRoutes);

// Serve Frontend static assets from the parent/frontend directory
app.use(express.static(path.join(__dirname, '../frontend')));

// Fallback to index.html for single-page style behaviors
app.use((req, res) => {
    res.sendFile(path.join(__dirname, '../frontend/index.html'));
});

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

app.listen(PORT, () => {
    console.log(`Server is running in ${process.env.NODE_ENV || 'development'} mode on port ${PORT}`);
    console.log(`System Host (Referer origin check) set to: ${process.env.SYSTEM_HOST || 'http://localhost:5000'}`);
});
