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 { CrewDirectory } from "./crew-directory";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Crew" };

export default async function CrewPage() {
  if (!CREWING_ENABLED) notFound();

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

  // NOTE: site-staff "own site only" scoping (§8.7) needs a User↔Site link that
  // isn't modelled yet — deferred to a follow-up; for now all active crew show.
  const crew = await db.crewMember.findMany({
    where: { status: "EMPLOYEE" },
    orderBy: { name: "asc" },
    include: {
      currentRank: { select: { name: true } },
      assignments: {
        where: { status: { not: "SIGNED_OFF" } },
        orderBy: { signOnDate: "desc" },
        take: 1,
        include: { vessel: { select: { name: true } }, site: { select: { name: true } } },
      },
    },
  });

  const rows = crew.map((c) => {
    const a = c.assignments[0];
    return {
      id: c.id,
      name: c.name,
      employeeId: c.employeeId ?? "—",
      rank: c.currentRank?.name ?? "—",
      location: a?.vessel?.name ?? a?.site?.name ?? "—",
      status: a?.status ?? null,
    };
  });

  return <CrewDirectory crew={rows} />;
}
