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 { AttendanceCalendar } from "./attendance-calendar";
import type { Metadata } from "next";

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

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

  const session = await auth();
  if (!session?.user) redirect("/login");
  const role = session.user.role;
  if (!hasPermission(role, "view_attendance")) redirect("/dashboard"); // MPO has no attendance (R5)

  const cutoff = new Date();
  cutoff.setMonth(cutoff.getMonth() - 4);

  const assignments = await 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 } },
      attendance: { where: { date: { gte: cutoff } }, select: { date: true, status: true } },
    },
  });

  return (
    <AttendanceCalendar
      assignments={assignments.map((a) => ({
        id: a.id,
        crewName: a.crewMember.name,
        rank: a.rank.name,
        location: a.vessel?.name ?? a.site?.name ?? "—",
        marks: Object.fromEntries(a.attendance.map((m) => [m.date.toISOString().slice(0, 10), m.status])),
      }))}
      canEdit={hasPermission(role, "record_attendance")}
    />
  );
}
