import { string } from 'alga-js'
import fetchHelper from './fetchHelper'

// Backfill product Name+Value from m_product because the OData identifier
// returned on cust_commissionactivity rows is sometimes empty or just the
// internal value. Mutates the passed list in place — each entry only needs
// `mProductId` (used for the lookup) and `productName` (replaced on hit).
export default async function enrichProductNames(
  event: any,
  token: string,
  rows: Array<{ mProductId: number | null; productName: string | null | undefined }>,
): Promise<void> {
  if (!rows.length) return
  const ids = Array.from(
    new Set(
      rows
        .map((r) => Number(r.mProductId))
        .filter((id) => Number.isFinite(id) && id > 0),
    ),
  )
  if (!ids.length) return

  const byId = new Map<number, { name: string; value: string }>()
  const ingest = (r: any) => {
    if (!r) return
    // iDempiere REST always returns `id` as the row's PK; prefer it.
    const rawPid = r?.id ?? r?.M_Product_ID ?? r?.m_product_id
    const pid = typeof rawPid === 'object' && rawPid?.id != null ? Number(rawPid.id) : Number(rawPid)
    if (!Number.isFinite(pid)) return
    const name = String(r?.Name ?? r?.name ?? '').trim()
    const value = String(r?.Value ?? r?.value ?? '').trim()
    if (name || value) byId.set(pid, { name, value })
  }

  try {
    const filter = `M_Product_ID in (${ids.join(',')}) AND (IsActive eq 'Y' OR IsActive eq 'N')`
    const url = `models/m_product?$filter=${string.urlEncode(filter)}&$select=M_Product_ID,Name,Value&$top=${ids.length}`
    const res: any = await fetchHelper(event, url, 'GET', token, null)
    const records: any[] = Array.isArray(res?.records) ? res.records : []
    for (const r of records) ingest(r)
  } catch (err: any) {
    console.error('enrichProductNames batch fetch failed:', err?.message ?? err)
  }

  const missing = ids.filter((id) => !byId.has(id))
  if (missing.length) {
    await Promise.all(missing.map(async (id) => {
      try {
        const r: any = await fetchHelper(event, `models/m_product/${id}?$select=M_Product_ID,Name,Value`, 'GET', token, null)
        ingest(r)
      } catch {
        // best effort — leave the original identifier-based label
      }
    }))
  }

  for (const r of rows) {
    const hit = byId.get(Number(r.mProductId))
    if (!hit) continue
    const { name, value } = hit
    if (name && value && name !== value) r.productName = `${value} — ${name}`
    else if (name) r.productName = name
    else if (value) r.productName = value
  }
}
