import {FastifyReply} from 'fastify';
import {processM3U8Content, proxyRequest, streamToReadable} from './proxy.service';
import {ProxyRequest} from '../types';

export async function handleProxy(req: ProxyRequest, reply: FastifyReply) {
    const { url, referer, origin, userAgent } = req.query;

    if (!url) {
        return reply.code(400).send({ error: "No URL provided" });
    }

    try {
        const { response, contentType, isM3U8, contentLength } = await proxyRequest(url, {
            referer,
            origin,
            userAgent
        });

        reply.header('Access-Control-Allow-Origin', '*');
        reply.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
        reply.header('Access-Control-Allow-Headers', 'Content-Type, Range');
        reply.header('Access-Control-Expose-Headers', 'Content-Length, Content-Range, Accept-Ranges');

        if (contentType) {
            reply.header('Content-Type', contentType);
        }

        if (contentLength) {
            reply.header('Content-Length', contentLength);
        }

        if (contentType?.startsWith('image/') || contentType?.startsWith('video/')) {
            reply.header('Cache-Control', 'public, max-age=31536000, immutable');
        }

        reply.header('Accept-Ranges', 'bytes');

        if (isM3U8) {
            const text = await response.text();
            const baseUrl = new URL(response.url);

            const processedContent = processM3U8Content(text, baseUrl, {
                referer,
                origin,
                userAgent
            });

            return reply.send(processedContent);
        }

        return reply.send(streamToReadable(response.body!));

    } catch (err) {
        req.server.log.error(err);

        if (!reply.sent) {
            return reply.code(500).send({ error: "Internal Server Error" });
        }
    }
}