import fs from "fs/promises";
import path from "path";
import { NextResponse } from "next/server";
import { markFromNum } from "@/lib/content/zhouyi";

const MIME: Record<string, string> = {
  ".png": "image/png",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".gif": "image/gif",
  ".webp": "image/webp",
};

export async function GET(
  _request: Request,
  {
    params,
  }: {
    params: Promise<{ variant: string; guaNum: string; filename: string }>;
  },
) {
  const { variant, guaNum, filename } = await params;

  if (!/^\d{1,2}$/.test(guaNum) || !/^[\w.-]+\.(png|jpe?g|gif|webp)$/i.test(filename)) {
    return new NextResponse("Not found", { status: 404 });
  }

  const learnVariant = variant === "simplified" ? "simplified" : "traditional";
  const guaMark = await markFromNum(guaNum.padStart(2, "0").slice(-2), learnVariant);
  if (!guaMark) {
    return new NextResponse("Not found", { status: 404 });
  }

  const root =
    learnVariant === "simplified"
      ? path.join(process.cwd(), "content", "zhouyi", "docs", "other")
      : path.join(process.cwd(), "content", "zhouyi", "docs");

  const filePath = path.join(root, guaMark, path.basename(filename));

  try {
    const data = await fs.readFile(filePath);
    const ext = path.extname(filename).toLowerCase();
    return new NextResponse(data, {
      headers: {
        "Content-Type": MIME[ext] ?? "application/octet-stream",
        "Cache-Control": "public, max-age=86400, immutable",
      },
    });
  } catch {
    return new NextResponse("Not found", { status: 404 });
  }
}
