import { defineMiddleware } from "astro:middleware";

export const onRequest = defineMiddleware(async (_, next) => {
    const response = await next();

    const contentType = response.headers.get("Content-Type") || "";

    // Only modify HTML responses
    if (contentType.includes("text/html")) {
        const html = await response.text();

        // Optimize LCP image by setting fetchpriority="high" on the hero image
        // Target specific image by its alt text seen in PageSpeed Insights
        const optimizedHtml = html.replace(
            /<img([^>]*?)alt="Ascently app icon"([^>]*?)>/,
            (match, p1, p2) => {
                if (match.includes("fetchpriority=")) {
                    return match.replace(/fetchpriority="[^"]*"/, 'fetchpriority="high"');
                }
                return `<img${p1}alt="Ascently app icon" fetchpriority="high"${p2}>`;
            }
        );

        return new Response(optimizedHtml, {
            status: response.status,
            headers: response.headers,
        });
    }

    return response;
});
