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

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

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

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

  const vessels = await db.vessel.findMany({
    orderBy: { name: "asc" },
  });

  const suggestedCode = nextId("SITE", vessels.map((v) => v.code));

  return (
    <VesselsTable
      suggestedCode={suggestedCode}
      vessels={vessels.map((v) => ({
        id: v.id,
        code: v.code,
        name: v.name,
        isActive: v.isActive,
      }))}
    />
  );
}
