const express = require('express');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');

const customerRoutes = require('./routes/customers-route/customers-main-route');
const hostRoutes = require('./routes/hosts-route/hosts-main-route');
const userRoutes = require('./routes/users/main-route');

const cors = require('./util/cors');
const serverError = require('./util/server-error');
const rateLimiter = require('./util/rate-limiter');

const passport = require('./util/passport-config');
const multerConfig = require('./util/multer');

const { notifyCheckIns, deleteOldNotifications } = require('./cron-jobs');

notifyCheckIns();
deleteOldNotifications();

dotenv.config();

const app = express();

app.set('trust proxy', true);
app.use((req, res, next) => {
	res.removeHeader('Pragma');
	res.removeHeader('Expires');
	res.removeHeader('Cache-Control');
	res.setHeader('Cache-Control', 'public, max-age=604800');
	next();
});

app.use(express.static('public'));

app.use(bodyParser.json());
app.use(passport.initialize());
app.use(multerConfig);

app.use('/api/v1/customers', cors, customerRoutes);
app.use('/api/v1/host', cors, hostRoutes);
app.use('/api/v1/users', cors, userRoutes);

app.use(serverError);

app.use('*', (req, res) => {
	res.status(404).json({ success: false, message: 'Resource unavailable.' });
});

const httpPort = process.env.HTTP_PORT;
const server = app.listen(httpPort, () => {
	console.log(`HTTP Server is running on port ${httpPort}`);
});

// Import socket.io
const httpServer = server;
const socketIo = require('socket.io');
const io = socketIo(httpServer); // Create Socket.IO instance attached to the HTTP server

const { handleSocketIoConnection } = require('./ws/chat-socket-io'); // New controller for socket.io

io.on('connection', (socket) => handleSocketIoConnection(socket, io));

console.log(`Socket.IO server is running on port ${httpPort}`);
