import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, pantryItems, eq, asc } from "@epicure/db";
import { PantryManager } from "@/components/meal-plan/pantry-manager";
import { PantryPageHeader } from "@/components/pantry/pantry-page-header";

export const metadata: Metadata = {};

export default async function PantryPage() {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) return null;

  const items = await db.query.pantryItems.findMany({
    where: eq(pantryItems.userId, session.user.id),
    orderBy: asc(pantryItems.rawName),
  });

  const mappedItems = items.map((i) => ({
    id: i.id,
    rawName: i.rawName,
    quantity: i.quantity,
    unit: i.unit,
    expiresAt: i.expiresAt?.toISOString() ?? null,
  }));

  return (
    <div className="space-y-6">
      <PantryPageHeader items={mappedItems} />
      <PantryManager initialItems={mappedItems} />
    </div>
  );
}
