import { waitingRoomUniversal } from "./wslib-waiting-room-universal"

async function handleRequest(request) {
    const headers = request.headers
    const clientID = headers.get("cdn-src-ip") + headers.get("user-agent")  // Decided by the client to identify the access terminal
    if (!clientID) {
        return fetch(request)                           // Without terminal identifier, waiting room logic cannot be applied
    }
    const url = new URL(request.url)
    const roomID = `room_${url.hostname}`.replace(/\./g, "_")  // Decided by the client to determine which URL scope shares a waiting room
    const args = {
        waitingMax: 3,                                  // The maximum number of allowed waiting clients (global)
        connectedMax: 3,                                // The maximum number of allowed connected clients (global)
        quotaUnit: 1,                                   // Quota package size

        // The following parameters have the same meaning as in a single-node waiting room
        connectedTimeout: 15,                           // The duration after which data inserted into the connection pool is automatically deleted
        waitingTimeout: 30,                             // The duration after which data inserted into the waiting pool is automatically deleted
        waitingPageMaxRefreshInterval: 3,               // The maximum interval for refreshing the waiting page
        generateWaitingPage: null,                      // Customizable function to generate a waiting page; if not provided, the default page will be used
        generateBusyPage: null,                         // Customizable function to generate a busy page; if not provided, the default page will be used
    }

    const resp = await waitingRoomUniversal(request, roomID, clientID, args)
    // For testing convenience, disable browser caching
    resp.headers.delete('ETag')
    resp.headers.delete('Last-Modified')
    return resp
}
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})