const express = require('express');
const cors = require('cors');
const path = require('path');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
require('dotenv').config({ path: path.join(__dirname, '.env') });
const { sessionMiddleware } = require('./config/session');

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

console.log('🔍 Environment loaded from:', path.join(__dirname, '.env'));
console.log('📍 Connection URI:', process.env.CONNECTION_URI);

const app = express();

app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.set('trust proxy', 1);

/* ---------- CORS ---------- */
app.use(
    cors({
        origin:
            process.env.NODE_ENV === 'production'
                ? true               // same origin (Docker / prod)
                : 'http://localhost:3000',
        credentials: true,
    })
);

app.use(sessionMiddleware);

const server = app.listen(PORT, "0.0.0.0", () => {
    console.log(`Server listening on port ${PORT}`);
});

/* ---------- Mongo + Socket ---------- */
require('./config/database')(mongoose);
require('./config/socket')(server);

/* ---------- Serve React build ---------- */
if (process.env.NODE_ENV === 'production') {
    const buildPath = path.resolve(__dirname, 'build');

    app.use(express.static(buildPath));

    app.get('*', (req, res) => {
        res.sendFile(path.join(buildPath, 'index.html'));
    });
}

module.exports = { server };
