/**
 * GET /api/materials/price-list-versions/available
 *
 * Price list versions a new product can be priced in right away:
 *   - version active AND its price list active
 *   - ValidFrom <= today (future versions are not "available" yet)
 * Joined in Node from two bounded reads (no $expand). Used by the quick
 * product modal to pre-select "every active & available version".
 */
import { string } from 'alga-js'
import refreshTokenHelper from '../../../utils/refreshTokenHelper'
import errorHandlingHelper from '../../../utils/errorHandlingHelper'
import fetchHelper from '../../../utils/fetchHelper'

const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const today = new Date().toISOString().slice(0, 10)

  const [plRes, plvRes]: any[] = await Promise.all([
    fetchHelper(event, `models/m_pricelist?$filter=${string.urlEncode('IsActive eq true')}&$top=200`, 'GET', token, null),
    fetchHelper(event, `models/m_pricelist_version?$filter=${string.urlEncode('IsActive eq true')}&$orderby=${string.urlEncode('ValidFrom desc')}&$top=500`, 'GET', token, null)
  ])

  const priceLists: Record<string, any> = {}
  for (const pl of (plRes?.records || [])) priceLists[String(pl.id)] = pl

  const seenPriceList = new Set<string>()
  const records = (plvRes?.records || [])
    .map((v: any) => {
      const pl = priceLists[String(v?.M_PriceList_ID?.id)]
      if (!pl) return null
      const validFrom = String(v?.ValidFrom || '').slice(0, 10)
      if (validFrom && validFrom > today) return null
      const isLatest = !seenPriceList.has(String(pl.id))
      seenPriceList.add(String(pl.id))
      return {
        id: v.id,
        name: v.Name || '',
        validFrom,
        isLatest,
        priceListId: pl.id,
        priceList: pl.Name || '',
        isSOPriceList: pl?.IsSOPriceList ?? pl?.isSOPriceList ?? false,
        isTaxIncluded: pl?.IsTaxIncluded ?? pl?.isTaxIncluded ?? false,
        currency: pl?.C_Currency_ID?.identifier || '',
        organizationId: v?.AD_Org_ID?.id ?? 0,
        organization: v?.AD_Org_ID?.identifier || ''
      }
    })
    .filter(Boolean)
    .sort((a: any, b: any) => a.priceList.localeCompare(b.priceList) || b.validFrom.localeCompare(a.validFrom))

  return { status: 200, records, 'row-count': records.length }
}

export default defineEventHandler(async (event) => {
  let data: any = {}
  try {
    data = await handleFunc(event)
  } catch (err: any) {
    try {
      const authToken = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch (error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
    }
  }
  return data
})
