import { defineEventHandler, setResponseHeader } from 'h3';

export default defineEventHandler(async (event) => {
    const acceptEncoding = event.headers.get('accept-encoding') || '';
    if (!acceptEncoding.includes('zstd')) return;

    const _end = event.node.res.end;
    //@ts-expect-error
    event.node.res.end = async (body: any, ...args: any[]) => {
        const buffer = typeof body === "string" ? new TextEncoder().encode(body) : body;

        if(buffer)
        {
            setResponseHeader(event, "Content-Encoding", "zstd");
            setResponseHeader(event, "Vary", "Accept-Encoding");
            //@ts-expect-error
            _end.call(event.node.res, await Bun.zstdCompress(buffer), ...args);
        }
        else
        {
            //@ts-expect-error
            _end.call(event.node.res, body, ...args);
        }
    };
});