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

export const metadata: Metadata = { title: "Accounting Code Management" };

export default async function AdminAccountsPage() {
  const session = await auth();
  if (!session?.user) redirect("/login");

  if (!hasPermission(session.user.role, "manage_vessels_accounts")) redirect("/dashboard");

  // Fetch full tree: top-level categories with sub-categories and their items
  const topCategories = await db.account.findMany({
    where: { parentId: null },
    orderBy: { code: "asc" },
    include: {
      children: {
        orderBy: { code: "asc" },
        include: {
          children: { orderBy: { code: "asc" } },
        },
      },
    },
  });

  // Flat list of all accounts for the parent selector in forms
  const allAccounts = await db.account.findMany({
    orderBy: { code: "asc" },
    select: { id: true, code: true, name: true, parentId: true },
  });

  return <AccountsTable topCategories={topCategories} allAccounts={allAccounts} />;
}
