const WebSocket = require("ws");
const { URL } = require('url');
const { routeMessage } = require("./routes");
const { auth } = require("./middleware/auth");
const { setupPing } = require("./utils/ping");
require("dotenv").config();

const api_version = '1.1.0';

const wss = new WebSocket.Server({ port: 4004 });
console.log("WebSocket сервер запущен на порту 4004");


wss.on("connection", async (ws, request) => {     
    const url = new URL(request.url, `http://${request.headers.host}`);
    const params = Object.fromEntries(url.searchParams.entries());
    const uuid = params.uuid ?? ws.protocol;

    if (!uuid) return ws.close();

    const user = await auth(uuid);
    if (!user) return ws.close();

    try {
        const user = await auth(uuid);
        if (!user) return ws.close();

        ws.user = user;
        ws.send(JSON.stringify({ connection: "success", api_version, user: {name: ws.user.name, id: ws.user.id } }));

        // Periodic ping to maintain a connection
        setupPing(ws);

        ws.on("message", (raw) => {
            try {
                const message = JSON.parse(raw);
                routeMessage(wss, ws, message);
            } catch (e) {
                console.error("❌ Invalid message:", raw);
                ws.send(JSON.stringify({ error: "Invalid message format" }));
            }
        });

        ws.on("close", () => {
            console.log("🔌 Client disconnected");
        });
        ws.on("error", (err) => console.error("❌ WS error:", err));
    } catch (err) {
        console.error("❌ Auth error:", err);
        ws.close();
    }
});