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 config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)
  const query = getQuery(event)

  let qryFilter = ''
  const queries = ['value', 'name', 'upc', 'sku', 'm_pricelist_version_id', 'm_warehouse_id', 'org_id', 'm_product_id', 'like', 'filter'] //'m_pricelist_id', 'm_attributeset_id', 'm_product_id', 'm_product_category_id', 'salesrep_id', 'issold',
  for(let qry of queries) {
    if(query?.[qry]) {
      if(qryFilter !== '') {
        qryFilter += ' AND '
      }
      //@ts-ignore
      const newQry = ''+query[qry].replaceAll('eq.', '').replaceAll('fts.', '')+''
      if(qry == 'value') {
        qryFilter += `product_value:${newQry} `
      } else if(qry == 'name') {
        qryFilter += `(product_name:*${newQry}* OR sku:${newQry} OR upc:${newQry} OR mpn:${newQry} OR asin:${newQry} OR value:${newQry})`
      } else if(qry == 'm_pricelist_version_id') {
        qryFilter += `pricelist_version_id:${newQry}`
      } else if(qry == 'm_warehouse_id') {
        qryFilter += `warehouse_id:${newQry}`
      } else if(qry == 'org_id') {
        qryFilter += `ad_org_id:${newQry}`
      } else if(qry == 'like') {
        qryFilter += `${newQry}*`
      } else if(qry == 'filter') {
        qryFilter += `(product_name:*${newQry}* OR sku:${newQry} OR upc:${newQry} OR mpn:${newQry} OR asin:${newQry} OR value:${newQry})`
      } else {
        qryFilter += `${qry}:${newQry}`
      }
    }
    console.log(qryFilter)
    // the queries result: product_value:${newQry} AND (product_name:${newQry} OR sku:${newQry} OR upc:${newQry} OR mpn:${newQry} OR asin:${newQry})
  }

  if(qryFilter) {
    qryFilter = `q=(${qryFilter})`
    // the queries result: q=(product_value:${newQry} AND (product_name:${newQry} OR sku:${newQry} OR upc:${newQry} OR mpn:${newQry} OR asin:${newQry}))
  }

  const res: any = await elasticHelper(`m_product/_search?q=${qryFilter || 'pretty'}`, 'GET', null)
  if(res) {
    data['records'] = res?.hits?.hits?.map((item: any) => {
      return {
        id: item._source.m_product_id,
        Name: item._source.product_name,
        Value: item._source.product_value,
        SKU: item._source.sku,
        UPC: item._source.upc,
        Strapi_Product_documentId: item._source.strapi_product_documentid,
        ...item._source
      }
    }) || []
  }

  return data
}

export default defineEventHandler(async (event: any) => {
  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
})