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 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, sites] = await Promise.all([
    db.vessel.findMany({
      orderBy: { name: "asc" },
      include: { site: { select: { name: true } } },
    }),
    db.site.findMany({ where: { isActive: true }, orderBy: { name: "asc" }, select: { id: true, name: true } }),
  ]);

  return (
    <VesselsTable
      vessels={vessels.map((v) => ({
        id: v.id,
        code: v.code,
        name: v.name,
        siteId: v.siteId ?? null,
        siteName: v.site?.name ?? null,
        isActive: v.isActive,
      }))}
      sites={sites}
    />
  );
}
