import {PRIVATE_API_URL} from "$env/static/private";
import {fetch} from "undici";

export async function POST({params, request, cookies}){
    const cookie = cookies.get("user");
    const body = await request.json();

    const res = await fetch(`${PRIVATE_API_URL}/game/${params.game_id}/session/${params.session_id}/turn`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Cookie": `user=${cookie}`,
            "Accept-Encoding": "identity"
        },
        body: JSON.stringify(body),
        duplex: "half"
    });

    const reader = res.body.getReader();
    const stream = new ReadableStream({
        async start(controller) {
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;
                controller.enqueue(value);
            }
            controller.close();
        }
    });

    return new Response(stream, {
        headers: {
            "Content-Type": "text/event-stream",
            "Cache-Control": "no-cache"
        }
    });
}
