import { PageKey } from "@prisma/client";
import { PageContentForm } from "@/admin/components/PageContentForm";
import { AdminAutoLayout } from "@/admin/layout/AdminAutoLayout";
import { requirePermission } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

const defaults = [
  {
    body: "Just Chill Nepal is growing as a Nepal-focused media platform with entertaining, useful, and cinematic content.",
    key: PageKey.HOME,
    subtitle: "Videos, shorts, culture, food, people, lifestyle, and stories from Nepal.",
    title: "Explore Nepal with Just Chill Nepal"
  },
  {
    body: "Just Chill Nepal shares videos, shorts, culture, food, lifestyle, people stories, and useful content for everyone who loves Nepal.",
    key: PageKey.ABOUT,
    subtitle: "A chill way to discover Nepal.",
    title: "About Just Chill Nepal"
  },
  {
    body: "Reach out for collaborations, sponsorships, content suggestions, or story ideas.",
    key: PageKey.CONTACT,
    subtitle: "Work with Just Chill Nepal.",
    title: "Contact and Collaborations"
  }
];

const pageOrder: PageKey[] = [PageKey.HOME, PageKey.ABOUT, PageKey.CONTACT];

export default async function AdminPagesPage() {
  await requirePermission("pages");

  for (const page of defaults) {
    await prisma.pageContent.upsert({
      create: page,
      update: {},
      where: { key: page.key }
    });
  }

  const pages = await prisma.pageContent.findMany({
    orderBy: { key: "asc" }
  });

  const orderedPages = pageOrder
    .map((key) => pages.find((page) => page.key === key))
    .filter((page): page is NonNullable<typeof page> => Boolean(page));

  return (
    <AdminAutoLayout
      description="Update public page copy, buttons, hero images, and SEO for Home, About, and Contact."
      eyebrow="Page control"
      title="Editable pages"
      width="wide"
    >
      <div className="admin-pages-stack">
        {orderedPages.map((page) => (
          <PageContentForm key={page.id} page={page} />
        ))}
      </div>
    </AdminAutoLayout>
  );
}
