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"

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)
  const query = getQuery(event)
  const organizationId = query?.org ?? getCookie(event, 'organizationId')

  let filterQuery = `isSOTrx eq false AND DocStatus eq 'CO' AND AD_Org_ID eq ${organizationId}`
  if(query?.search) {
    filterQuery = `${filterQuery} AND contains(DocumentNo,'`+query.search+`')`
  }
  const res: any = await event.context.fetch(`models/c_order?$filter=${string.urlEncode(filterQuery)}&$expand=c_orderline($expand=m_product_id),m_warehouse_id&$orderby=${string.urlEncode('c_order_id desc')}`, 'GET', token, null)
  if(res) {
    const filteredData = res.records.filter((item: any) => {
      return item.c_orderline.filter((it: any) => Number(it.QtyEntered ?? 1) < Number(it.QtyDelivered ?? 0))
    })
    data = res
    data.records = filteredData.slice(0, 5)
  }
  /*const res: any[] = await postgrestHelper(event, `xx_open_purchase_orders`, 'GET', null)
  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) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})