import { db } from "@/lib/db";
import { PantryClient } from "@/components/pantry/pantry-client";

export const metadata = { title: "Pantry & Freezer" };
export const dynamic = "force-dynamic";

export default async function PantryPage() {
  const [items, locations, plants] = await Promise.all([
    db.item.findMany({
      where: { kind: "CONSUMABLE", active: true },
      orderBy: [{ location: { name: "asc" } }, { name: "asc" }],
      select: {
        id: true, name: true, description: true, quantity: true, unit: true,
        storedAt: true, bestBefore: true, source: true, plantId: true, notes: true,
        pantryCategory: true, pantrySubcategory: true, pricePaid: true, priceUnit: true,
        location: { select: { id: true, name: true } },
        plant: { select: { id: true, commonName: true, variety: true } },
      },
    }),
    db.location.findMany({
      where: {
        active: true,
        OR: [
          { name: { equals: "Kitchen", mode: "insensitive" } },
          { path: { contains: "Kitchen", mode: "insensitive" } },
        ],
      },
      orderBy: { path: "asc" },
      select: { id: true, name: true, path: true },
    }),
    db.plant.findMany({ where: { active: true }, orderBy: { commonName: "asc" }, select: { id: true, commonName: true, variety: true } }),
  ]);

  const serialized = items.map(i => ({
    id: i.id,
    name: i.name,
    description: i.description,
    quantity: Number(i.quantity),
    unit: i.unit,
    packageSize: i.description,
    storedAt: i.storedAt,
    bestBefore: i.bestBefore,
    source: i.source,
    notes: i.notes,
    pantryCategory: i.pantryCategory,
    pantrySubcategory: i.pantrySubcategory,
    pricePaid: i.pricePaid != null ? Number(i.pricePaid) : null,
    priceUnit: i.priceUnit,
    locationId: i.location?.id ?? null,
    locationName: i.location?.name ?? null,
    plantId: i.plant?.id ?? null,
    plantName: i.plant ? `${i.plant.commonName}${i.plant.variety ? ` (${i.plant.variety})` : ""}` : null,
  }));

  return <PantryClient initialItems={serialized} locations={locations} plants={plants} />;
}
