import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, shoppingLists, shoppingListMembers, eq, desc } from "@epicure/db";
import { ShoppingListsPageContent } from "@/components/shopping-lists/shopping-lists-page-content";

export const metadata: Metadata = {};

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

  const [lists, memberships] = await Promise.all([
    db.query.shoppingLists.findMany({
      where: eq(shoppingLists.userId, session.user.id),
      orderBy: desc(shoppingLists.createdAt),
      with: { items: { columns: { id: true, checked: true } } },
    }),
    db.query.shoppingListMembers.findMany({
      where: eq(shoppingListMembers.userId, session.user.id),
      with: { list: { with: { user: true } } },
    }),
  ]);

  return (
    <ShoppingListsPageContent
      lists={lists.map((list) => ({
        id: list.id,
        name: list.name,
        generatedAt: list.generatedAt ? list.generatedAt.toISOString() : null,
        totalItems: list.items.length,
        checkedItems: list.items.filter((i) => i.checked).length,
      }))}
      sharedLists={memberships.map((m) => ({
        id: m.list.id,
        name: m.list.name,
        ownerName: m.list.user?.name ?? "Unknown",
        role: m.role,
      }))}
    />
  );
}
