import "dotenv/config";
import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/redis-adapter";
import { jwtMiddleware } from "modules/socketJWTmiddleware";
import { pubClient, subClient } from "modules/redis";
import { handleConnectDispatch } from "socket-events/connect-dispatch";
import router from "routes/router";
import { handleSendMessage } from "socket-events/send-message";
import { handleConnectPilot } from "socket-events/connect-pilot";
import { handleConnectDesktop } from "socket-events/connect-desktop";
import cookieParser from "cookie-parser";
import cors from "cors";
import { authMiddleware } from "modules/expressMiddleware";
import "modules/chron";

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

export const io = new Server(server, {
	adapter: createAdapter(pubClient, subClient),
	cors: {},
});
io.use(jwtMiddleware);

io.on("connection", (socket) => {
	console.log("New socket connection", socket.id);
	socket.on("connect-dispatch", handleConnectDispatch(socket, io));
	socket.on("connect-pilot", handleConnectPilot(socket, io));
	socket.on("connect-desktop", handleConnectDesktop(socket, io));
	socket.on("send-message", handleSendMessage(socket, io));
});

app.use(cors());
app.use(express.json());
app.use(cookieParser());
app.use(authMiddleware as any);
app.use(router);

server.listen(process.env.DISPATCH_SERVER_PORT, () => {
	console.log(`Server running on port ${process.env.DISPATCH_SERVER_PORT}`);
});
