const twitch = require('twitch-m3u8')

exports.handler = async function (event, context) {
    const user = event.queryStringParameters?.user;
    if(user)
    {
        try
        {
            var playlist = await twitch.getStream(user, true);
            return { headers: {"content-type":"application/vnd.apple.mpegurl; charset=utf-8"}, statusCode: 200, body: playlist };
        }
        catch(err)
        {
            return { headers: {"content-type":"text/plain"}, statusCode: 404, body: "user "+user+" not found" };
        }
    }
    else
    {
        const vod = event.queryStringParameters?.vod;
        if(vod)
        {
            try
            {
                var playlist = await twitch.getVod(vod, true);
                return { headers: {"content-type":"application/vnd.apple.mpegurl; charset=utf-8"}, statusCode: 200, body: playlist };
            }
            catch(err)
            {
                return { headers: {"content-type":"text/plain"}, statusCode: 404, body: "vod "+vod+" not found" };
            }
        }
        else
        {
            return { headers: {"content-type":"text/plain"}, statusCode: 404, body: "Usage:\ntwitch?user=<username>\ntwitch?vod=<vodid>" };
        }
    }
};