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 { PipelineBoard } from "./pipeline-board";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Recruitment pipeline" };

export default async function PipelinePage({ params }: { params: Promise<{ id: string }> }) {
  if (!CREWING_ENABLED) notFound();

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

  const { id } = await params;
  const requisition = await db.requisition.findUnique({
    where: { id },
    include: { rank: { select: { name: true } }, vessel: { select: { name: true } }, site: { select: { name: true } } },
  });
  if (!requisition) notFound();

  const applications = await db.application.findMany({
    where: { requisitionId: id },
    include: { crewMember: { select: { id: true, name: true, type: true, experienceMonths: true } } },
    orderBy: { createdAt: "asc" },
  });

  const canManage = hasPermission(role, "manage_candidates");
  // Candidates available to add: in the pool (not employees) and not already applied here.
  const appliedIds = new Set(applications.map((a) => a.crewMemberId));
  const pool = canManage
    ? (await db.crewMember.findMany({
        where: { status: { not: "EMPLOYEE" } },
        orderBy: { name: "asc" },
        select: { id: true, name: true, type: true },
      })).filter((c) => !appliedIds.has(c.id))
    : [];

  return (
    <PipelineBoard
      requisition={{
        id: requisition.id,
        code: requisition.code,
        rank: requisition.rank.name,
        location: requisition.vessel?.name ?? requisition.site?.name ?? "—",
        status: requisition.status,
      }}
      applications={applications.map((a) => ({
        id: a.id,
        stage: a.stage,
        crewName: a.crewMember.name,
        isExHand: a.crewMember.type === "EX_HAND",
        experienceMonths: a.crewMember.experienceMonths,
      }))}
      pool={pool}
      canManage={canManage}
    />
  );
}
