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

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

  //const res: any = await event.context.fetch(`models/c_bpartner/${id}?$expand=c_order($select=c_order_id,c_doctype_id,c_doctypetarget_id,documentno,dateacct,grandtotal;$filter=${string.urlEncode("docstatus eq 'CO'")}),m_inout($select=m_inout_id,c_doctype_id,documentno,dateacct,iscommissioned;$filter=${string.urlEncode("docstatus eq 'CO'")}),c_invoice($select=c_invoice_id,c_doctype_id,documentno,dateacct,grandtotal;$filter=${string.urlEncode("docstatus eq 'CO'")}),r_request($select=r_request_id)`, 'GET', token, null)
  const res: any = await event.context.fetch(`models/c_bpartner/${id}?$expand=c_order($select=c_order_id,c_doctype_id,c_doctypetarget_id,documentno,dateacct,grandtotal,isSOTrx),m_inout($select=m_inout_id,c_doctype_id,documentno,dateacct,iscommissioned,isSOTrx),c_invoice($select=c_invoice_id,c_doctype_id,documentno,dateacct,grandtotal,isSOTrx),r_request($select=r_request_id)`, 'GET', token, 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: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})