import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { redirect } from "next/navigation";
import { nextId } from "@/lib/id-generators";
import { VendorsTable } from "./vendors-table";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Vendor Registry" };

export default async function AdminVendorsPage() {
  const session = await auth();
  if (!session?.user) redirect("/login");
  if (!hasPermission(session.user.role, "manage_vendors")) redirect("/dashboard");

  const vendors = await db.vendor.findMany({
    orderBy: { name: "asc" },
    include: {
      _count: { select: { vendorPrices: true } },
      contacts: { orderBy: [{ isPrimary: "desc" }, { createdAt: "asc" }] },
    },
  });

  const suggestedVendorId = nextId("VND", vendors.map((v) => v.vendorId));

  return (
    <VendorsTable
      suggestedVendorId={suggestedVendorId}
      vendors={vendors.map((v) => ({
        id: v.id,
        vendorId: v.vendorId,
        name: v.name,
        gstin: v.gstin ?? null,
        address: v.address ?? null,
        pincode: v.pincode ?? null,
        isVerified: v.isVerified,
        isActive: v.isActive,
        itemCount: v._count.vendorPrices,
        contacts: v.contacts.map((c) => ({
          name: c.name,
          role: c.role ?? "",
          mobile: c.mobile ?? "",
          email: c.email ?? "",
          isPrimary: c.isPrimary,
        })),
      }))}
    />
  );
}
