import { createReadStream } from "fs";
import { join } from "path";

export default async (req: Request) => {
  try {
    const body = await req.json();

    if (body.lang && body.pathname) {
      const filePath = join(import.meta.dirname, `./data/${body.lang}.json`);

      const redirectUrl = await new Promise<string | null>(
        (resolve, reject) => {
          const stream = createReadStream(filePath, {
            emitClose: false,
            encoding: "utf-8",
            highWaterMark: 1024,
          });
          const data: string[] = [];

          stream.on("data", (chunk) => {
            if (data.length === 3) {
              data.shift();
            }
            data.push(chunk.toString());
            // Since we strip trailing slash (in the trailingSlash middleware) before entering this middleware,
            // we need check matching paths both including and excluding trailing slash.
            const re = new RegExp(`"${body.pathname}\/?":"([^"]+)"`);

            const match = data.join("").match(re);
            if (match?.[1]) {
              stream.destroy();
              resolve(match[1]);
            }
          });

          stream.on("error", (err) => {
            console.error("Stream error:", err);
            stream.destroy();
            reject(err);
          });

          stream.on("end", () => {
            stream.destroy();
            resolve(null); // No match found
          });
        }
      );

      if (redirectUrl) {
        // Make sure to exclude trailing slash in the redirectUrl to avoid an extra middleware roundtrip
        const redirectUrlWithoutTrailingSlash = redirectUrl.endsWith("/")
          ? redirectUrl.slice(0, -1)
          : redirectUrl;
        if (redirectUrlWithoutTrailingSlash === body.pathname) {
          console.log(
            `[scandic-redirect] recieved ${body.pathname}, found ${redirectUrlWithoutTrailingSlash}, no-op`
          );
          return new Response("Not Found", { status: 404 });
        }
        console.log(
          `[scandic-redirect] recieved ${body.pathname}, return ${redirectUrlWithoutTrailingSlash}, success`
        );
        return new Response(redirectUrlWithoutTrailingSlash);
      }
    }
    console.log(`[scandic-redirect] recieved ${body.pathname}, not found`);
    return new Response("Not Found", { status: 404 });
  } catch (error) {
    return new Response("Bad request", { status: 400 });
  }
};
