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

const memberRoutes = require('./routes/members/members-main-route');
const driverRoutes = require('./routes/drivers/drivers-main-route');
const conventionRoutes = require('./routes/conventions/conventions-main-route');

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

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

const { Server } = require('socket.io');
const { createServer } = require('node:http');
require('./crons/delete-file');

dotenv.config();

const app = express();
const server = createServer(app);

app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.json());

const drivers_passport = require('./util/passport/drivers/driver-passport-config');
const members_passport = require('./util/passport/members/member-passport-config');
const convention_passport = require('./util/passport/conventions/convention-passport-config');

app.use(drivers_passport.initialize());
app.use(members_passport.initialize());
app.use(convention_passport.initialize());

const { deleteUploadedFiles } = require('./util/file-handlers');

const USE_EXTERNAL_FILE_SERVER = process.env.USE_EXTERNAL_FILE_SERVER === 'true';

//test
app.use('/api/v1/files', cors, require('./routes/files/files'));
//test

app.use(multerConfig);
if (!USE_EXTERNAL_FILE_SERVER) {
	app.use('/api/v1/files', cors, require('./routes/files/files'));
}

if (process.env.ALLOW_EMAIL_SENDING_ROUTE === 'true') {
	app.use('/api/v1/emails', cors, require('./routes/emails/emails'));
}

app.use('/api/v1/member', cors, memberRoutes);
app.use('/api/v1/driver', cors, driverRoutes);
app.use('/api/v1/convention', cors, conventionRoutes);

////////////////////////DELETE IF THERE IS SEPARATE SUPER ADMIN SYSTEM..////////////////////////
//currently used for development purposes only
// if there is a separate super admin system, this should be removed
const superAdminRoutes = require('./routes/super-admin');

app.use('/api/v1/super-admin', cors, superAdminRoutes);
// app.use('/api/v1/super-admin', cors, superAdminRoutes);
////////////////////////DELETE IF THERE IS SEPARATE SUPER ADMIN SYSTEM..////////////////////////

app.use(serverError);

app.get('/', (req, res) => {
	return res.status(200).json({
		success: true,
		message: 'Welcome to the JCI Worldcon API',
	});
});

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

const port = process.env.PORT ? parseInt(process.env.PORT) : 3000;

if (process.env.USE_SOCKET === 'true') {
	const io = new Server(server);

	io.on('connection', (socket) => {
		socket.on('join-room', (room) => {
			console.log('A user joined the bus locations room');
			socket.join(room);
		});

		socket.on('location-update', (data) => {
			console.log('Location update received:', data);
			socket.to('bus-locations').emit('location-update', data);
		});

		socket.on('disconnect', () => {
			console.log('A user disconnected');
		});
	});
}

const startServer = () => {
	server.listen(port, '0.0.0.0', () => {
		console.log(`Server is running on port ${port}`);
	});
};

startServer();
