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

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

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

  const session = await auth();
  if (!session?.user) redirect("/login");
  const role = session.user.role;
  const canDocs = hasPermission(role, "verify_site_records");
  const canBankEpf = hasPermission(role, "verify_bank_epf");
  if (!canDocs && !canBankEpf) redirect("/dashboard");

  const [docs, bank, epf] = await Promise.all([
    canDocs
      ? db.seafarerDocument.findMany({
          where: { verificationStatus: "PENDING" },
          orderBy: { createdAt: "asc" },
          include: {
            crewMember: {
              select: {
                name: true,
                assignments: { where: { status: { not: "SIGNED_OFF" } }, take: 1, include: { vessel: { select: { name: true } }, site: { select: { name: true } } } },
              },
            },
          },
        })
      : [],
    canBankEpf
      ? db.bankDetail.findMany({ where: { verificationStatus: "PENDING" }, orderBy: { createdAt: "asc" }, include: { crewMember: { select: { name: true } } } })
      : [],
    canBankEpf
      ? db.epfDetail.findMany({ where: { verificationStatus: "PENDING" }, orderBy: { createdAt: "asc" }, include: { crewMember: { select: { name: true } } } })
      : [],
  ]);

  return (
    <VerificationManager
      docs={docs.map((d) => {
        const a = d.crewMember.assignments[0];
        return {
          id: d.id,
          crewName: d.crewMember.name,
          location: a?.vessel?.name ?? a?.site?.name ?? "—",
          docType: d.docType,
          number: d.number,
          expiryDate: d.expiryDate?.toISOString() ?? null,
          submitted: d.createdAt.toISOString(),
        };
      })}
      bank={bank.map((b) => ({ crewMemberId: b.crewMemberId, crewName: b.crewMember.name, accountName: b.accountName, accountNumber: b.accountNumber, ifsc: b.ifsc, bankName: b.bankName }))}
      epf={epf.map((e) => ({ crewMemberId: e.crewMemberId, crewName: e.crewMember.name, uan: e.uan, aadhaarLast4: e.aadhaarLast4, pfNumber: e.pfNumber }))}
      canDocs={canDocs}
      canBankEpf={canBankEpf}
    />
  );
}
