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

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

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

  const session = await auth();
  if (!session?.user) redirect("/login");
  const role = session.user.role;
  const canApply = hasPermission(role, "apply_leave");
  const canDecide = hasPermission(role, "decide_leave");
  if (!canApply && !canDecide) redirect("/dashboard"); // MPO has no leave screen (R1)

  const [assignments, requests] = await Promise.all([
    db.crewAssignment.findMany({
      where: { status: { not: "SIGNED_OFF" } },
      orderBy: { crewMember: { name: "asc" } },
      include: { crewMember: { select: { name: true } }, rank: { select: { name: true } }, vessel: { select: { name: true } }, site: { select: { name: true } } },
    }),
    db.leaveRequest.findMany({
      orderBy: { createdAt: "desc" },
      take: 100,
      include: { assignment: { include: { crewMember: { select: { name: true } }, rank: { select: { name: true } }, vessel: { select: { name: true } }, site: { select: { name: true } } } } },
    }),
  ]);

  return (
    <LeaveManager
      assignments={assignments.map((a) => ({ id: a.id, crewName: a.crewMember.name, rank: a.rank.name, location: a.vessel?.name ?? a.site?.name ?? "—" }))}
      requests={requests.map((r) => ({
        id: r.id,
        crewName: r.assignment.crewMember.name,
        rank: r.assignment.rank.name,
        location: r.assignment.vessel?.name ?? r.assignment.site?.name ?? "—",
        type: r.type,
        status: r.status,
        fromDate: r.fromDate.toISOString(),
        toDate: r.toDate.toISOString(),
        reason: r.reason,
      }))}
      canApply={canApply}
      canDecide={canDecide}
    />
  );
}
