import { promises as fs } from "node:fs";
import path from "node:path";

import { getImage } from "@/lib/admin/blogDb";

export const runtime = "nodejs";

function safeFileName(name: string): string | null {
  let decoded = "";
  try {
    decoded = decodeURIComponent(name || "").trim();
  } catch {
    return null;
  }
  if (!decoded) return null;
  if (decoded.includes("..")) return null;
  if (decoded.includes("/") || decoded.includes("\\")) return null;
  if (path.basename(decoded) !== decoded) return null;
  return decoded;
}

function guessMimeType(fileName: string): string {
  const lower = fileName.toLowerCase();
  if (lower.endsWith(".png")) return "image/png";
  if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "image/jpeg";
  if (lower.endsWith(".webp")) return "image/webp";
  if (lower.endsWith(".gif")) return "image/gif";
  if (lower.endsWith(".svg")) return "image/svg+xml";
  return "application/octet-stream";
}

async function tryReadFile(fullPath: string): Promise<Uint8Array | null> {
  try {
    const buf = await fs.readFile(fullPath);
    return new Uint8Array(buf);
  } catch {
    return null;
  }
}

export async function GET(_req: Request, ctx: { params: { fileName: string } }) {
  const fileName = safeFileName(ctx.params.fileName);
  if (!fileName) return new Response("Not found", { status: 404 });

  const fromDb = await getImage(fileName);
  if (fromDb) {
    return new Response(fromDb.bytes, {
      status: 200,
      headers: {
        "content-type": fromDb.mimeType || guessMimeType(fileName),
        "cache-control": "public, max-age=31536000, immutable",
      },
    });
  }

  // Fallback for local dev / older builds: serve from public/ or content/ if present.
  const publicPath = path.join(process.cwd(), "public", "blog", "images", fileName);
  const contentPath = path.join(process.cwd(), "content", "blog", "images", fileName);
  const bytes = (await tryReadFile(publicPath)) || (await tryReadFile(contentPath));
  if (!bytes) return new Response("Not found", { status: 404 });

  return new Response(bytes, {
    status: 200,
    headers: {
      "content-type": guessMimeType(fileName),
      "cache-control": "public, max-age=31536000, immutable",
    },
  });
}
