import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { redirect } from "next/navigation";
import { TermsTable } from "./terms-table";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Terms & Conditions" };

export default async function TermsPage() {
  const session = await auth();
  if (!session?.user) redirect("/login");
  if (!hasPermission(session.user.role, "manage_terms")) redirect("/dashboard");

  const [terms, categories] = await Promise.all([
    db.termsCondition.findMany({
      orderBy: [{ category: { sortOrder: "asc" } }, { isActive: "desc" }, { sortOrder: "asc" }, { createdAt: "asc" }],
      include: { category: { select: { name: true } } },
    }),
    db.termsCategory.findMany({ orderBy: [{ sortOrder: "asc" }, { name: "asc" }], select: { name: true } }),
  ]);

  return (
    <TermsTable
      categoryNames={categories.map((c) => c.name)}
      terms={terms.map((t) => ({
        id: t.id,
        categoryName: t.category.name,
        text: t.text,
        isDefault: t.isDefault,
        isActive: t.isActive,
      }))}
    />
  );
}
