import { string } from 'alga-js'
import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"
import postgrestHelper from "../../../utils/postgrestHelper"
import elasticHelper from "../../../utils/elasticHelper"
import fetchHelper from "../../../utils/fetchHelper"

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)
  const query = getQuery(event)

  let newFilter = ''
  let qryFilter = {}
  const qryRecords = []
  const queries = ['m_product_id', 'value', 'name', 'upc', 'sku', 'm_product_category_id', 'salesrep_id', 'issold'] //'m_pricelist_id', 'm_pricelist_version_id', 'm_warehouse_id', 'm_attributeset_id'
  const valFilter = query?.['filter'] ?? ''
  for(let qry of queries) {
    if(query?.[qry]) {
      if(newFilter !== '') {
        newFilter += ' OR '
      }
      //newFilter += `${newFilter === '' ? '?' : '&'}${qry}=${query[qry]}`
      //@ts-ignore
      const newQry = query[qry].replaceAll('eq.', '').replaceAll('fts.', '')
      if(qry == 'value') {
        newFilter += `contains(Value,'${valFilter}')`
        qryFilter = {
          ...qryFilter,
          'records.Value': valFilter
        }
        qryRecords.push({ match: { 'records.Value': valFilter } })
      } else if(qry == 'name') {
        newFilter += `contains(Name,'${valFilter}')`
        qryFilter = {
          ...qryFilter,
          'records.Name': valFilter
        }
        qryRecords.push({ match: { 'records.Name': valFilter } })
      } else if(qry == 'upc') {
        newFilter += `contains(UPC,'${valFilter}')`
        qryFilter = {
          ...qryFilter,
          'records.UPC': valFilter
        }
        qryRecords.push({ match: { 'records.UPC': valFilter } })
      } else if(qry == 'sku') {
        newFilter += `contains(SKU,'${valFilter}')`
        qryFilter = {
          ...qryFilter,
          'records.SKU': valFilter
        }
        qryRecords.push({ match: { 'records.SKU': valFilter } })
      } else {
        newFilter += `${qry} eq ${newQry}`
        qryFilter = {
          ...qryFilter,
          ['records.'+qry]: valFilter
        }
        qryRecords.push({ match: { ['records.'+qry]: valFilter } })
      }
    }
  }

  if(query?.['org_id']) {
    newFilter = `${newFilter.length >= 1 ? '('+newFilter+') AND ' : ''}AD_Org_ID eq ${query['org_id']}`
  }

  //@ts-ignore
  /*const res: any[] = await postgrestHelper(event, `xx_search_product${newFilter}`, 'GET', null)
  if(res) {
    data['records'] = res
  }*/
 
  const res: any = await fetchHelper(event, `models/m_product?$expand=m_product_category_id($select=Name,IsDefault),M_ProductPrice&$filter=${string.urlEncode(newFilter)}`, 'GET', token, null)
  if(res) {
    data = res

    if(res.records.length >= 1) {
      data.records = res.records.filter((it: any) => {
        let filterResult: boolean = false

        if(it?.M_Locator_ID?.M_Warehouse_ID?.id && query?.['m_warehouse_id']) {
          //@ts-ignore
          const newQry = query['m_warehouse_id'].replaceAll('eq.', '').replaceAll('fts.', '')
          if(Number(newQry) === Number(it.M_Locator_ID.M_Warehouse_ID.id)) {
            filterResult = true
          }
        } else {
          if(!it?.M_Locator_ID) {
            filterResult = true
          }
        }

        if(it?.M_ProductPrice?.length >= 1 && query?.['m_pricelist_version_id']) {
          //@ts-ignore
          const newQry = query['m_pricelist_version_id'].replaceAll('eq.', '').replaceAll('fts.', '')
          if(it.M_ProductPrice.filter((i: any) => Number(newQry) === Number(i.M_PriceList_Version_ID.id)).length >= 1) {
            filterResult = true
          } else {
            filterResult = false
          }
        } else {
          if(query?.['m_pricelist_version_id']) {
            filterResult = false
          }
        }

        return filterResult
      }).map((im: any) => {
        if(im?.M_ProductPrice?.length >= 1 && query?.['m_pricelist_version_id']) {
          //@ts-ignore
          const newQry = query['m_pricelist_version_id'].replaceAll('eq.', '').replaceAll('fts.', '')
          const productPrice = im.M_ProductPrice.filter((i: any) => Number(newQry) === Number(i.M_PriceList_Version_ID.id))
          if(productPrice.length >= 1) {
            im.M_ProductPrice = productPrice[0]
          }
        }
        return im
      })
    }
  }

  /*const res: any = await elasticHelper(`m_product/_search?pretty`, 'POST', {
    query: {
      //...qryFilter,
      nested: {
        path: 'records',
        query: {
          bool: {
            must: qryRecords
          }
        }
      },
      query_string: {
        query: query['search']
      }
    }
  })
  if(res) {
    data = res
  }*/
  
  return data
}

export default defineEventHandler(async (event) => {
  let data: any = {}

  try {
    data = await handleFunc(event)
  } catch(err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch(error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})