import { pgGetMaterials, pgGetItemGroups, pgGetSettings, pgGetMaterialsStock } from '@/lib/postgres/data-access';
import StorePageClient from '@/components/store/store-page-client';
import { getCurrencySymbolAsync } from '@/lib/server-currency';

export const dynamic = 'force-dynamic';

export default async function StorePage() {
  const [materialsResult, itemGroupsResult, settings] = await Promise.all([
    pgGetMaterials({ page: 1, pageSize: 5000 }),
    pgGetItemGroups ? pgGetItemGroups({ page: 1, pageSize: 500 }) : Promise.resolve({ items: [] }),
    pgGetSettings(),
  ]);

  const allMaterials = (materialsResult.items || []) as any[];
  const storeItems = allMaterials.filter(
    (m) => m.storeEnabled === true || m.storeEnabled === 'true'
  );

  const warehousesEnabled = (settings as any)?.warehousesEnabled === true || (settings as any)?.warehousesEnabled === 'true';

  let storeItemsWithStock: any[] = storeItems;
  if (warehousesEnabled) {
    const storeItemIds = storeItems.map((m: any) => String(m.id || ''));
    const stockMap = storeItemIds.length > 0 ? await pgGetMaterialsStock(storeItemIds) : {};
    storeItemsWithStock = storeItems.map((m: any) => ({
      ...m,
      stockQuantity: stockMap[String(m.id || '')] ?? null,
    }));
  }

  const itemGroups = (itemGroupsResult?.items || []) as any[];

  const storeName = String((settings as any)?.storeName || 'متجرنا الإلكتروني');
  const storeDescription = String((settings as any)?.storeDescription || '');
  const storeContactPhone = String((settings as any)?.storeContactPhone || '');
  const storeCurrencySymbol = await getCurrencySymbolAsync();

  return (
    <StorePageClient
      items={storeItemsWithStock}
      itemGroups={itemGroups}
      storeName={storeName}
      storeDescription={storeDescription}
      storeContactPhone={storeContactPhone}
      currencySymbol={storeCurrencySymbol}
    />
  );
}
