import { defineSisHandler } from "../../../utils/listings/routeHelper"
import { enrichWithProducts } from "../../../utils/sisMatching"

// GET /api/sales/sms/products-defaults?orderSourceId=&productIds=1,2,3
// Prefill for the "List products" modal: internal price (order source's price
// list, else the app default), qty on hand (minus returns), ASIN, name.
export default defineSisHandler(async ({ event, token, f }) => {
  const q = getQuery(event)
  const orderSourceId = Number(q.orderSourceId)
  const ids = String(q.productIds || '').split(',').map(s => Number(s.trim())).filter(n => n > 0).slice(0, 200)
  if (!orderSourceId) return { status: 400, message: 'orderSourceId is required' }
  if (!ids.length) return { status: 200, records: [] }
  const orderSource: any = await f(`models/c_ordersource/${orderSourceId}`)
  if (!orderSource?.id) return { status: 404, message: 'Order source not found' }
  const config: any = useRuntimeConfig(event)
  const priceListId = Number(orderSource?.M_PriceList_ID?.id) || config.public?.pricelistid || '101'
  const enrich = await enrichWithProducts(event, token, Number(orderSource?.AD_Org_ID?.id) || 0, ids, priceListId)
  return { status: 200, records: ids.map(id => enrich.get(id) || { productId: id, productName: '', productValue: '', asin: null, internalPrice: null, internalQtyOnHand: null, returnQtyOnHand: 0, isBom: false, strapiProductDocumentId: null }) }
})
