import { waitingRoomSingle } from "./wslib-waiting-room-single"

async function handleRequest(request) {
    const headers = request.headers
    const url = new URL(request.url)
    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 roomID = url.hostname                         // Decided by the client to determine which URL scope shares a waiting room
    const args = {
        connectedTimeout: 15,                           // The duration after which data inserted into the connection pool is automatically deleted
        connectedMax: 1,                                // The maximum number of allowed connected clients
        waitingTimeout: 30,                             // The duration after which data inserted into the waiting pool is automatically deleted
        waitingMax: 2,                                  // The maximum number of allowed waiting clients
        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 waitingRoomSingle(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))
})