import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { CREWING_ENABLED } from "@/lib/feature-flags";
import { redirect, notFound } from "next/navigation";
import { RanksManager } from "./ranks-manager";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Ranks & Documents" };

export default async function AdminRanksPage() {
  // Dark unless the crewing module is switched on.
  if (!CREWING_ENABLED) notFound();

  const session = await auth();
  if (!session?.user) redirect("/login");
  if (!hasPermission(session.user.role, "manage_ranks")) redirect("/dashboard");

  const ranks = await db.rank.findMany({
    orderBy: [{ name: "asc" }],
    include: { docRequirements: { orderBy: { docType: "asc" } } },
  });

  // Flatten to plain props (no Date/Decimal crosses the server→client boundary).
  const rows = ranks.map((r) => ({
    id: r.id,
    code: r.code,
    name: r.name,
    description: r.description,
    category: r.category,
    isSeafarer: r.isSeafarer,
    grantsLogin: r.grantsLogin,
    isActive: r.isActive,
    parentId: r.parentId,
    docRequirements: r.docRequirements.map((d) => ({
      id: d.id,
      docType: d.docType,
      isMandatory: d.isMandatory,
      note: d.note,
    })),
  }));

  return <RanksManager ranks={rows} />;
}
