const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

const { initSocket } = require('./socket');
initSocket(server);

const port = 3000;

const connectDB = require('./config/connectDB');
const routes = require('./routes/index.routes');

const cookieParser = require('cookie-parser');
const cors = require('cors');
const path = require('path');
require('dotenv').config();
const { generalLimiter } = require('./config/rateLimiter');

connectDB();

const helmet = require('helmet');

// Fix: Trust proxy để lấy IP thật từ Cloudflare/Nginx
app.set('trust proxy', 1);

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(
    helmet({
        crossOriginResourcePolicy: { policy: 'cross-origin' },
    }),
);

app.use(cors({ origin: process.env.URL_CLIENT, credentials: true }));

// Fix: Rate limiter tổng quát toàn server chống DDoS
app.use('/api', generalLimiter);

// Serve uploads folder
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

routes(app);

app.use((err, req, res, next) => {
    const statusCode = err.statusCode || 500;
    res.status(statusCode).json({
        success: false,
        message: err.message || 'Lỗi server',
    });
});

server.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});
