import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { StatusBadge } from "@/components/admin/StatusBadge";
import { PostArticle } from "@/components/public/PostArticle";
import { requireUser } from "@/lib/auth/dal";
import { parseIdParam } from "@/lib/params";
import { getPostById } from "@/lib/services/posts";

export const metadata: Metadata = { title: "Preview post" };

/** Renders the post exactly as the public site would — drafts included. */
export default async function PostPreviewPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const user = await requireUser();
  const { id: rawId } = await params;
  const id = parseIdParam(rawId);
  if (id === null) notFound();

  const post = await getPostById(id);
  if (!post) notFound();
  if (user.role !== "admin" && post.authorId !== user.id) notFound();

  return (
    <div>
      <div className="mb-8 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-warning/40 bg-warning/10 px-4 py-3 text-sm">
        <p className="flex items-center gap-2 text-warning">
          <span className="font-medium">Preview</span>
          <StatusBadge status={post.status} />
        </p>
        <Link
          href={`/admin/posts/${post.id}/edit`}
          className="font-medium text-warning underline underline-offset-4"
        >
          Back to editor
        </Link>
      </div>
      <PostArticle post={post} />
    </div>
  );
}
