import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
import fs from "fs";
import { createHash } from "crypto";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export default async function setupRoute(context, options) {
    options = options || {};
    options.block =
        options.block ||
        /(\.png)|(\.jpg)|(\.svg)|(\.otf)|(\.woff)|(\.woff2)|(\.ttf)|(\.mp3)|(google)|(facebook)|(ada\.support)/;
    options.cache = options.cache || /(\.js)|(\.css)/;

    await context.route(options.block, (route, request) => route.abort());

    await context.route(options.cache, async (route, request) => {
        const fileName = resolve(
            __dirname,
            "cache",
            createHash("md5").update(request.url()).digest("hex")
        );
        if (fs.existsSync(fileName)) {
            await route.fulfill({
                body: fs.readFileSync(fileName),
                contentType: /\.js$/.test(request.url())
                    ? "application/javascript"
                    : "text/css",
            });
        } else {
            const response = await route.fetch();
            fs.writeFileSync(fileName, await response.body());
            await route.fulfill({
                response,
            });
        }
    });
}
