import { notFound } from "next/navigation";
import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import { requireAuth } from "@/lib/auth/guards";
import { prisma } from "@/lib/db";
import { PageHeader } from "@/components/app/page-header";
import { RepurposeClient } from "@/components/app/repurpose-client";
import { Button } from "@/components/ui/button";

type Format = "blog" | "social_thread" | "newsletter";
type Content = { title: string; body: string } | null;

export default async function RepurposePage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await requireAuth();

  const episode = await prisma.episode.findUnique({
    where: { id },
    select: {
      userId: true,
      title: true,
      script: { select: { id: true } },
      repurposed: { orderBy: { createdAt: "desc" } },
    },
  });
  if (!episode) notFound();
  if (episode.userId !== session.user.id && session.user.role !== "admin") notFound();

  // Latest content per format.
  const initial: Record<Format, Content> = { blog: null, social_thread: null, newsletter: null };
  for (const r of episode.repurposed) {
    const key = r.type as Format;
    if (key in initial && !initial[key]) initial[key] = r.content as unknown as Content;
  }

  return (
    <>
      <Button asChild variant="ghost" size="sm" className="mb-2">
        <Link href={`/episodes/${id}`}>
          <ArrowLeft className="h-4 w-4" /> Back to episode
        </Link>
      </Button>
      <PageHeader
        title="Repurpose content"
        description={`Turn "${episode.title}" into a blog post, social thread, or newsletter.`}
      />
      <RepurposeClient episodeId={id} initial={initial} />
    </>
  );
}
