import { findRedirect, getPublishedPost } from "@/features/public-api/queries";
import { apiJson, SLUG_PARAM } from "@/features/public-api/respond";
import type { ApiNotFoundResponse, ApiPostResponse } from "@/features/public-api/types";
import { blogPath } from "@/lib/site";

/** GET /api/v1/posts/<slug> — one published article, or where its old URL now points. */
export async function GET(_request: Request, { params }: RouteContext<"/api/v1/posts/[slug]">) {
  const { slug } = await params;
  const notFound: ApiNotFoundResponse = { error: "not_found" };

  if (!SLUG_PARAM.test(slug) || slug.length > 200) {
    return apiJson(notFound, { status: 404 });
  }

  const post = await getPublishedPost(slug);
  if (post) return apiJson({ post } satisfies ApiPostResponse);

  const redirect = await findRedirect(blogPath(slug));
  return apiJson(redirect ? { ...notFound, redirect } : notFound, {
    status: 404,
    cache: "public, max-age=0, s-maxage=30",
  });
}
