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

export default defineEventHandler(async (event: any) => {
  let data: any = {}
  let tracking_service: string = ''
  let tracking_inout: string = ''
  const query = getQuery(event)

  if(query?.service && query?.no) {
    try {
      if((query?.service ?? 'dhl').toLowerCase() === 'sendcloud') {
        const res: any = await sendcloudHelper(`tracking/${query.no}`, 'GET', null)
        if(res) {
          data = res
          data['tracking_content'] = (res?.statuses || []).map((item: any) => {
            return {
              timestamp: item.carrier_update_timestamp,
              title: item.carrier_message,
              description: `${item.carrier_message}, ${item.carrier_code} ${item.parcel_status_history_id}`,
              status: item.parent_status,
            }
          })
        }
        tracking_service = 'sendcloud'
      } else if((query?.service ?? 'dhl').toLowerCase() === 'dhl' && query?.inout_id) {
        let dhlCustomData = {}
        const tokenCustom = await getTokenHelper(event)
        //@ts-ignore
        const respInout: any = await fetchHelper(event, 'models/m_inout/'+query.inout_id+'?$expand=c_order_id,ad_org_id', 'GET', tokenCustom, null)
      
        if(respInout?.C_Order_ID?.C_OrderSource_ID?.id) {
          //@ts-ignore
          const respOrderSource: any = await fetchHelper(event, 'models/c_ordersource/'+respInout.C_Order_ID.C_OrderSource_ID.id, 'GET', tokenCustom, null)
          if(respOrderSource?.DHL_USE_CUSTOM == true && respOrderSource?.DHLURL) {
            dhlCustomData = {
              api: {
                dhlurl: respOrderSource.DHLURL,
                dhlkey: respOrderSource.DHLKEY,
                dhlsecret: respOrderSource.DHLSECRET,
                dhluser: respOrderSource.DHLUSER,
                dhlpass: respOrderSource.DHLPASS,
                iscustom: respOrderSource.DHL_USE_CUSTOM,
                dhl_billing_number_de: respOrderSource.dhl_billing_number_de || '63291441520101',
                dhl_billing_number_int: respOrderSource.dhl_billing_number_int || '63291441525301'
              }
            }
          }
        }

        const countryCode = respInout?.C_Order_ID?.M_Warehouse_ID?.C_Location_ID?.C_Country_ID?.id ?? '' //'101'
        const countryName = respInout?.C_Order_ID?.M_Warehouse_ID?.C_Location_ID?.C_Country_ID?.identifier ?? '' //'Germany'
        const config = dhlCustomData?.api ? dhlCustomData : useRuntimeConfig()
        let trackShipmentUrl = `track/shipments?trackingNumber=${query.no}`
        if(countryCode === '101' || countryName === 'Germany') {
          trackShipmentUrl = `parcel/de/tracking/v0/shipments?xml=%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20standalone%3D%22no%22%3F%3E%3Cdata%20appname%3D%22${string.urlEncode(config.api.dhluser ?? 'logyou')}%22%20language-code%3D%22de%22%20password%3D%22${string.urlEncode(config.api.dhlpass ?? 'vjasdk!vi4868vcAhc')}%22%20piece-code%3D%2200340434781760028311%22%20request%3D%22d-get-piece-detail%22%20%2F%3E`
          dhlCustomData = {
            ...dhlCustomData,
            headers: {
              'Authorization': 'Basic a09NWmxDa2RZMjdPdnBHS2lVZmZaOGxVaWdOaGN2V246VzlZQXJuVUlmTXN1eWJ2Rg=='
            }
          }
        } else {
          dhlCustomData = {
            ...dhlCustomData,
            headers: {
              'DHL-API-Key': 'kOMZlCkdY27OvpGKiUffZ8lUigNhcvWn'
            }
          }
        }
        const res: any = await dhlTrackingHelper(event, dhlCustomData, trackShipmentUrl, 'GET', null)
        if(res) {
          data = res
          data['tracking_content'] = (res?.shipments?.[0]?.events || []).map((item: any) => {
            return {
              timestamp: item.timestamp,
              title: item.status,
              description: item?.description ?? item?.remark ?? `${item?.location?.address?.addressLocality ?? ''}, ${item?.location?.address?.countryCode ?? ''} ${item?.location?.address?.postalCode ?? ''}`,
              status: item.statusCode,
            }
          })
        }
        tracking_service = 'dhl'
        tracking_inout = query?.inout_id ?? ''
      }
    } catch(error: any) {
      data['error'] = error
      tracking_service = 'error'
    }
  }

  data['tracking_service'] = tracking_service
  data['tracking_inout'] = tracking_inout
  
  return data
})