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

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

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

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

  const [crew, ranks, vessels, sites] = await Promise.all([
    db.crewMember.findMany({
      orderBy: { name: "asc" },
      include: {
        currentRank: { select: { name: true } },
        appliedRank: { select: { name: true } },
        assignments: { where: { status: { not: "SIGNED_OFF" } }, select: { id: true }, take: 1 },
        _count: { select: { assignments: true, applications: true } },
      },
    }),
    db.rank.findMany({ where: { isActive: true }, orderBy: { name: "asc" }, select: { id: true, code: true, name: true } }),
    db.vessel.findMany({ where: { isActive: true }, orderBy: { name: "asc" }, select: { id: true, name: true } }),
    db.site.findMany({ where: { isActive: true }, orderBy: { name: "asc" }, select: { id: true, name: true } }),
  ]);

  return (
    <AdminCrewManager
      crew={crew.map((c) => ({
        id: c.id,
        name: c.name,
        status: c.status,
        type: c.type,
        source: c.source,
        email: c.email,
        phone: c.phone,
        employeeId: c.employeeId,
        appliedRankId: c.appliedRankId,
        currentRankId: c.currentRankId,
        currentRank: c.currentRank?.name ?? null,
        experienceMonths: c.experienceMonths,
        hasActiveAssignment: c.assignments.length > 0,
        removable: c._count.assignments === 0 && c._count.applications === 0,
      }))}
      ranks={ranks}
      vessels={vessels}
      sites={sites}
    />
  );
}
