import OrdersPageClient from "@/components/orders/OrdersPageClient";
import { orderRepository } from "@/lib/repositories/orderRepository";
import { shopRepository } from "@/lib/repositories/shopRepository";
import { resolveShopScope, restrictedShopIds } from "@/lib/storeScope";
import { getCurrentUser } from "@/lib/currentUser";

export const dynamic = "force-dynamic";

type SearchParams = Promise<Record<string, string | string[] | undefined>>;

function firstParam(value: string | string[] | undefined) {
  return Array.isArray(value) ? value[0] : value;
}

function normalizeStatus(value: string | undefined) {
  if (!value) return "all";
  if (value === "READY_TO_SHIP") return "incoming";
  return value;
}

export default async function OrdersPage({ searchParams }: { searchParams: SearchParams }) {
  const params = await searchParams;
  const status = normalizeStatus(firstParam(params.status));
  const q = firstParam(params.q);
  const shopId = firstParam(params.shop_id);
  const dateFrom = firstParam(params.date_from);
  const dateTo = firstParam(params.date_to);
  const page = Number(firstParam(params.page) || "1") || 1;
  const pageSize = Number(firstParam(params.page_size) || "25") || 25;
  const sort = firstParam(params.sort) === "create_time" ? "create_time" : "update_time";

  const current = await getCurrentUser();
  const shops = current ? await shopRepository.findScopeOptionsForUser(current) : [];
  const activeShopId = resolveShopScope(shopId, shops) || undefined;
  const shopIds = restrictedShopIds(current?.role, activeShopId, shops);

  const [result, statusCounts] = await Promise.all([
    orderRepository.findMany({
      shopId: activeShopId,
      shopIds,
      status: status || undefined,
      search: q || undefined,
      dateFrom: dateFrom ? new Date(`${dateFrom}T00:00:00`) : null,
      dateTo: dateTo ? new Date(`${dateTo}T23:59:59`) : null,
      page,
      pageSize,
      sort,
    }),
    orderRepository.getStats(activeShopId, shopIds),
  ]);

  const { orders, itemsByOrderSn, total } = result;

  return (
    <OrdersPageClient
      initial={{
        shops,
        activeShopId: activeShopId || null,
        status,
        sort,
        q: q || null,
        dateFrom: dateFrom || null,
        dateTo: dateTo || null,
        page,
        pageSize,
        renderedAt: new Date().toISOString(),
        total,
        statusCounts,
        orders: orders.map((o) => ({
          ...o,
          createTime: o.createTime?.toISOString() ?? null,
          updateTime: o.updateTime?.toISOString() ?? null,
          shippingDocumentPrintedAt: o.shippingDocumentPrintedAt?.toISOString() ?? null,
          pickupReadyAt: o.pickupReadyAt?.toISOString() ?? null,
          pickupScheduledAt: o.pickupScheduledAt?.toISOString() ?? null,
          shipByDate: o.shipByDate?.toISOString() ?? null,
        })),
        itemsByOrderSn: Object.fromEntries(
          Object.entries(itemsByOrderSn).map(([sn, rows]) => [
            sn,
            rows.map((i) => ({
              ...i,
            })),
          ])
        ),
      }}
    />
  );
}
