import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import path from 'path';
import { WebSocketServer } from 'ws';
import { fileURLToPath } from 'url';
import { setupDocker } from './includes/docker.js';
import { handleWebSocket } from './includes/websocket.js';
import { generateLoginLink, handleAutoLogin } from './includes/auth.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
const PORT = parseInt(process.env.PORT, 10);

app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));

const docker = setupDocker();
const wss = new WebSocketServer({ noServer: true });

wss.on('connection', (ws, req) => handleWebSocket(ws, req, docker));

app.post('/generate-login-link', generateLoginLink);
app.get('/auto-login/:linkId', handleAutoLogin);
app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'public', 'index.html')));

const server = app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
server.on('upgrade', (request, socket, head) => {
  wss.handleUpgrade(request, socket, head, (ws) => wss.emit('connection', ws, request));
});