import TokensPageClient from "@/components/tokens/TokensPageClient";
import { shopRepository } from "@/lib/repositories/shopRepository";
import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/currentUser";

export const dynamic = "force-dynamic";

export default async function TokensPage() {
  const current = await getCurrentUser();
  const [shops, scopeShops, orderStats] = await Promise.all([
    current ? shopRepository.findManyForUser(current) : Promise.resolve([]),
    current ? shopRepository.findScopeOptionsForUser(current) : Promise.resolve([]),
    prisma.shopeeOrder.groupBy({ by: ["shopId"], _count: { _all: true }, _sum: { totalAmount: true } }),
  ]);
  const statsByShop = new Map(orderStats.map((row) => [row.shopId, { orders: row._count._all, revenue: row._sum.totalAmount || 0 }]));
  return (
    <TokensPageClient
      shops={shops.map((shop) => ({
        ...shop,
        connectedAt: shop.connectedAt.toISOString(),
        tokenExpiredAt: shop.tokenExpiredAt?.toISOString() ?? null,
        refreshTokenExpiredAt: shop.refreshTokenExpiredAt.toISOString(),
        lastRefreshAt: shop.lastRefreshAt.toISOString(),
        tokenHealth: shop.tokenHealth,
        orders: statsByShop.get(shop.shopId)?.orders || 0,
        revenue: statsByShop.get(shop.shopId)?.revenue || 0,
      }))}
      historicalShops={scopeShops.filter((shop) => !shop.connected).map((shop) => ({
        shopId: shop.shopId,
        shopName: shop.shopName,
        orders: statsByShop.get(shop.shopId)?.orders || 0,
        revenue: statsByShop.get(shop.shopId)?.revenue || 0,
      }))}
    />
  );
}
