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 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)

  const res: any = await fetchHelper(event, `models/m_product?$expand=M_Locator_ID,M_ProductPrice,M_Storage&$filter=${query?.q || ''}`, '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
      })
    }
  }
  
  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
})