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 dhlHelper from "../../../../utils/dhlHelper"

const handleInoutFunc = async (event: any, authToken: any = null, id) => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)

  const resp: any = await fetchHelper(event, 'models/m_inout/'+id, 'PUT', token, {
    TrackingNo: null,
    DHL_Shipment_Code: null,
    DHL_Routing_Code: null,
    DHL_Label_Base64: null,
    IsCommissioned: false,
    IsCommissionedConfirmed: false,
    ack_commissioned_laravel: false,
    tableName: 'M_Inout'
  })
  if(resp) {
    data['shipment'] = resp
    data['status'] = 200
    data['message'] = ''
  }

  return data
}

export default defineEventHandler(async (event) => {
  let data: any = {}
  const body = await readBody(event)

  try {
    try {
      data = await handleInoutFunc(event, null, body.inOutId)
    } catch(err: any) {
      try {
        let authToken: any = await refreshTokenHelper(event)
        data = await handleInoutFunc(event, authToken, body.inOutId)
      } catch(error: any) {
        data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
        forceLogoutHelper(event, data)
      }
    }
  } catch(error: any) {
    data['status'] = 500
    data['message'] = error?.message ?? 'Other Parcel is not being properly cancelled!'
  }

  return data
})