import { router, publicProcedure, protectedProcedure } from '@/src/trpc/trpc-index' import { getSuspendedSkuIds, getNextDeliveryDateWithCapacity, getAllSkusSummary as getAllSkusSummaryInDb, getAllTagsForCache, getAllTagProductMappings, getAvailabilityForCache, getAllProductsForCache, getAllDeliverySlotsForCache, } from '@/src/dbService' import { generateSignedUrlsFromS3Urls, generateSignedUrlFromS3Url, scaffoldAssetUrl } from '@/src/lib/s3-client' import { getRegionConstValues } from '@/src/lib/const-store' import { CONST_KEYS } from '@/src/lib/const-keys' // Re-export with original name for backwards compatibility export const getNextDeliveryDate = getNextDeliveryDateWithCapacity export async function scaffoldProducts(regionId: number) { // Scoped DB reads directly (NOT the in-memory product-store) so the output // contains ONLY in-region SKUs/products/tags. const [productsData, suspendedSkuIds, allTags, tagMappings, deliveryRows] = await Promise.all([ getAllProductsForCache(regionId), getSuspendedSkuIds(regionId), getAllTagsForCache(regionId), getAllTagProductMappings(regionId), getAllDeliverySlotsForCache(regionId), ]) const suspended = new Set(suspendedSkuIds) const products = productsData.filter(item => Boolean(item.id) && !suspended.has(item.id)) // Latest in-region delivery slot per SKU (matches the old DESC first-match // semantics of getNextDeliveryDateWithCapacity). const nextDeliveryBySku = new Map() for (const row of deliveryRows) { const prev = nextDeliveryBySku.get(row.skuId) if (!prev || row.deliveryTime > prev) { nextDeliveryBySku.set(row.skuId, row.deliveryTime) } } // Format products to match the expected response structure const formattedProducts = products.map((product) => { const nextDeliveryDate = nextDeliveryBySku.get(product.id) ?? null return { id: product.id, name: product.name, shortDescription: product.shortDescription, unit: product.unitNotation, unitNotation: product.unitNotation, incrementStep: product.incrementStep, productQuantity: product.productQuantity, storeId: product.storeId ?? null, isOutOfStock: product.isOutOfStock, nextDeliveryDate: nextDeliveryDate ? nextDeliveryDate.toISOString() : null, images: scaffoldAssetUrl((product.images as string[]) || []), productType: product.productType || 'item', isComboOnly: product.isComboOnly, isOffer: product.isOffer, price: Number(product.price ?? 0), marketPrice: product.marketPrice != null ? Number(product.marketPrice) : null, flashPrice: product.flashPrice != null ? Number(product.flashPrice) : null, isFlashAvailable: product.isFlashAvailable, }; }) // Order tags by the region's admin-defined tagsOrder (unknown tags go to the end). const regionConsts = await getRegionConstValues(regionId) const tagsOrderRaw = regionConsts[CONST_KEYS.tagsOrder] let tagsOrderIds: number[] = [] if (Array.isArray(tagsOrderRaw)) { tagsOrderIds = tagsOrderRaw.map((id: any) => parseInt(id)).filter((id: number) => !isNaN(id)) } else if (typeof tagsOrderRaw === 'string') { tagsOrderIds = tagsOrderRaw.split(',').map((id: string) => parseInt(id.trim())).filter((id: number) => !isNaN(id)) } const tagsById = new Map(allTags.map((tag: any) => [tag.id, tag])) const orderedTags: any[] = [] for (const id of tagsOrderIds) { const tag = tagsById.get(id) if (tag) { orderedTags.push(tag) tagsById.delete(id) } } for (const tag of tagsById.values()) { orderedTags.push(tag) } const productIdsByTag = new Map() for (const mapping of tagMappings) { if (!productIdsByTag.has(mapping.tagId)) { productIdsByTag.set(mapping.tagId, []) } productIdsByTag.get(mapping.tagId)!.push(mapping.productId) } // Reorder each tag's product ids by the admin-defined sortOrder (unknown products go to the end). const reorderProductIds = (tagId: number, tagSortOrder: number[] | undefined) => { const current = productIdsByTag.get(tagId) || [] if (!Array.isArray(tagSortOrder) || tagSortOrder.length === 0) { return current } const ordered = tagSortOrder.filter((id: number) => current.includes(id)) const rest = current.filter((id: number) => !ordered.includes(id)) return [...ordered, ...rest] } const tags = orderedTags.map((tag: { id: number; tagName: string; tagDescription: string | null; imageUrl: string | null; isDashboardTag: boolean; relatedStores: unknown; sortOrder: number[] | null }) => ({ id: tag.id, tagName: tag.tagName, tagDescription: tag.tagDescription, imageUrl: tag.imageUrl ? scaffoldAssetUrl(tag.imageUrl) : null, isDashboardTag: tag.isDashboardTag, relatedStores: (tag.relatedStores as number[]) || [], productIds: reorderProductIds(tag.id, tag.sortOrder ?? undefined), })) return { products: formattedProducts, count: formattedProducts.length, tags, }; } export async function scaffoldAvailability(regionId: number) { const availability = await getAvailabilityForCache(regionId) return { availability, count: availability.length, }; } export const commonRouter = router({ getAllProductsSummary: protectedProcedure .query(async ({ ctx }) => { // Admin-only (the customer apps read the regional CDN cache files, not // this endpoint): return the caller's OWN region only. return scaffoldProducts(ctx.staffUser!.regionId) }), getAllSkusSummary: protectedProcedure .query(async ({ ctx }) => { // Admin-only SKU picker; scoped to the caller's region. const skus = await getAllSkusSummaryInDb(ctx.staffUser!.regionId) return { skus } }), });