import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { redirect } from "next/navigation";
import { ProductsTable } from "@/app/(portal)/admin/products/products-table";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Item Catalogue" };

export default async function InventoryItemsPage() {
  const session = await auth();
  if (!session?.user) redirect("/login");

  const products = await db.product.findMany({
    where: { isActive: true },
    orderBy: { name: "asc" },
    include: {
      lastVendor: true,
      _count: { select: { vendorPrices: true } },
    },
  });

  // canManage lets managers/admins see the Edit/Delete controls even from /inventory/items
  const canManage = hasPermission(session.user.role, "manage_products");

  return (
    <div className="max-w-6xl">
      <ProductsTable
        canManage={canManage}
        products={products.map((p) => ({
          id: p.id,
          code: p.code,
          name: p.name,
          description: p.description ?? null,
          lastPrice: p.lastPrice !== null ? Number(p.lastPrice) : null,
          lastVendorName: p.lastVendor?.name ?? null,
          updatedAt: p.updatedAt.toISOString(),
          isActive: p.isActive,
          vendorPriceCount: p._count.vendorPrices,
        }))}
      />
    </div>
  );
}
