import { describe, expect, it, afterAll, beforeAll } from "bun:test";
import { WebServer } from "./server";

describe("WebSocket Server", () => {
    // Start server on a random port
    const port = 0;

    beforeAll(() => {
        WebServer.start(port);
    });

    afterAll(() => {
        WebServer.stop();
    });

    it("should accept websocket connection and send welcome message", async () => {
        const port = WebServer.port;
        expect(port).toBeDefined();

        const ws = new WebSocket(`ws://localhost:${port}/ws`);

        const messagePromise = new Promise<any>((resolve) => {
            ws.onmessage = (event) => {
                resolve(JSON.parse(event.data as string));
            };
        });

        const msg = await messagePromise;
        expect(msg.type).toBe("WELCOME");
        expect(msg.message).toContain("Connected");

        ws.close();
    });

    it("should reject non-ws upgrade requests on /ws endpoint via http", async () => {
        const port = WebServer.port;
        // Just a normal fetch to /ws should fail with 426 Upgrade Required usually, 
        // but our implementation returns "WebSocket upgrade failed" 500 or undefined -> 101 Switching Protocols if valid.
        // If we send a normal GET request to /ws without Upgrade headers, server.upgrade(req) returns false.
        // So it returns status 500 "WebSocket upgrade failed" based on our code.

        const res = await fetch(`http://localhost:${port}/ws`);
        expect(res.status).toBe(500);
        expect(await res.text()).toBe("WebSocket upgrade failed");
    });
});
