import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { redirect } from "next/navigation";
import { ProductsTable } from "./products-table";
import type { Metadata } from "next";

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

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

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

  const canManage = hasPermission(session.user.role, "manage_products");

  return (
    <ProductsTable
      canManage={canManage}
      detailBase="/admin/products"
      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,
      }))}
    />
  );
}
