import { NextRequest } from "next/server";
import { z } from "zod";
import { getEntryById } from "@/server/repo";

const paramsSchema = z.object({ id: z.coerce.number().int().positive() });

export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  const raw = await ctx.params;
  const parsed = paramsSchema.safeParse(raw);
  if (!parsed.success) {
    return new Response(JSON.stringify({ error: parsed.error.flatten() }), {
      status: 400,
      headers: { "content-type": "application/json" },
    });
  }
  const id = parsed.data.id;
  const detail = await getEntryById(id);
  if (!detail) {
    return new Response(JSON.stringify({ error: "Not found" }), {
      status: 404,
      headers: { "content-type": "application/json" },
    });
  }
  return new Response(JSON.stringify(detail), {
    headers: {
      "content-type": "application/json",
      // Cache for 1h on CDN, allow stale while revalidating for a day
      "cache-control": "public, max-age=0, s-maxage=3600, stale-while-revalidate=86400",
    },
  });
}

export const runtime = "nodejs";
