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");

  // Own-site scoping (§8.7): a site-staff user with a home site sees only crew whose
  // active assignment is at that site. Without a home site they remain unscoped.
  let siteScopeId: string | null = null;
  if (session.user.role === "SITE_STAFF") {
    siteScopeId = (await db.user.findUnique({ where: { id: session.user.id }, select: { siteId: true } }))?.siteId ?? null;
  }

  const crew = await db.crewMember.findMany({
    where: {
      status: "EMPLOYEE",
      ...(siteScopeId ? { assignments: { some: { status: { not: "SIGNED_OFF" }, siteId: siteScopeId } } } : {}),
    },
    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} />;
}
