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

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

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

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

  const [requirements, vessels, ranks] = await Promise.all([
    db.vesselRankRequirement.findMany({
      orderBy: [{ vessel: { name: "asc" } }, { rank: { name: "asc" } }],
      include: { vessel: { select: { name: true } }, rank: { select: { name: true } } },
    }),
    db.vessel.findMany({ where: { isActive: true }, orderBy: { name: "asc" }, select: { id: true, name: true } }),
    db.rank.findMany({ where: { isActive: true }, orderBy: { name: "asc" }, select: { id: true, code: true, name: true } }),
  ]);

  return (
    <CrewStrengthManager
      requirements={requirements.map((r) => ({ id: r.id, vessel: r.vessel.name, rank: r.rank.name, minStrength: r.minStrength }))}
      vessels={vessels}
      ranks={ranks}
    />
  );
}
