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

export const metadata: Metadata = { title: "Account 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");

  const accounts = await db.account.findMany({ orderBy: { code: "asc" } });

  const suggestedCode = nextId("ACC", accounts.map((a) => a.code));

  return (
    <AccountsTable
      suggestedCode={suggestedCode}
      accounts={accounts.map((a) => ({
        id: a.id,
        code: a.code,
        name: a.name,
        description: a.description ?? null,
        isActive: a.isActive,
      }))}
    />
  );
}
