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"

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

  let newObjValue = {}
  if(body.shipperId) {
    newObjValue = {...newObjValue, 
      M_Shipper_ID: {
        id: body.shipperId,
        tableName: 'M_Shipper'
      }
    }
  }
  if(body.partnerLocationId) {
    newObjValue = {...newObjValue, 
      C_BPartner_Location_ID: {
        id: body.partnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.currencyId) {
    newObjValue = {...newObjValue, 
      C_Currency_ID: {
        id: body.currencyId,
        tableName: 'C_Currency'
      }
    }
  }
  if(body.uomLengthId) {
    newObjValue = {...newObjValue, 
      C_UOM_Length_ID: {
        id: body.uomLengthId,
        tableName: 'C_UOM'
      }
    }
  }
  if(body.uomWeightId) {
    newObjValue = {...newObjValue, 
      C_UOM_Weight_ID: {
        id: body.uomWeightId,
        tableName: 'C_UOM'
      }
    }
  }
  if(body.dotHazardClassOrDivisionId) {
    newObjValue = {...newObjValue, 
      DotHazardClassOrDivision: {
        id: body.dotHazardClassOrDivisionId
      }
    }
  }
  if(body.holdAddressId) {
    newObjValue = {...newObjValue, 
      HoldAddress_ID: {
        id: body.holdAddressId,
        tableName: 'c_bpartner_location'
      }
    }
  }
  if(body.homeDeliveryPremiumTypeId) {
    newObjValue = {...newObjValue, 
      HomeDeliveryPremiumType: {
        id: body.homeDeliveryPremiumTypeId
      }
    }
  }
  if(body.notificationTypeId) {
    newObjValue = {...newObjValue, 
      notificationType: {
        id: body.notificationTypeId
      }
    }
  }
  if(body.paymentRuleId) {
    newObjValue = {...newObjValue, 
      PaymentRule: {
        id: body.paymentRuleId
      }
    }
  }
  if(body.deliveryConfirmationTypeId) {
    newObjValue = {...newObjValue, 
      DeliveryConfirmationType: {
        id: body.deliveryConfirmationTypeId
      }
    }
  }
  if(body.documentNo) {
    newObjValue = {...newObjValue, documentNo: body.documentNo}
  }

  if(body.id) {
    const res: any = await fetchHelper(event, 'models/m_package/'+body.id, 'PUT', token, {
      isActive: body.isActive,
      description: body.description,
      dateReceived: body.dateReceived,
      receivedInfo: body.receivedInfo,
      trackingInfo: body.trackingInfo,
      shipDate: body.shipDate,
      boxCount: body.boxCount,
      cashOnDelivery: body.cashOnDelivery,
      deliveryConfirmation: body.deliveryConfirmation,
      dryIceWeight: body.dryIceWeight,
      handlingCharge: body.handlingCharge,
      height: body.height,
      homeDeliveryPremiumDate: body.homeDeliveryPremiumDate,
      homeDeliveryPremiumPhone: body.homeDeliveryPremiumPhone,
      insuredAmount: body.insuredAmount,
      latestPickupTime: body.latestPickupTime,
      length: body.length,
      price: body.price,
      priceActual: body.priceActual,
      rateInquiryMessage: body.rateInquiryMessage,
      shippingRespMessage: body.shippingRespMessage,
      surcharges: body.surcharges,
      trackingNo: body.trackingNo,
      weight: body.weight,
      width: body.width,
      dutiesShipperAccount: body.dutiesShipperAccount,
      shipperAccount: body.shipperAccount,
      notificationMessage: body.notificationMessage,
      isAccessible: body.isAccessible,
      isCargoAircraftOnly: body.isCargoAircraftOnly,
      isDryIce: body.isDryIce,
      isDutiable: body.isDutiable,
      isFutureDayShipment: body.isFutureDayShipment,
      isHazMat: body.isHazMat,
      isHoldAtLocation: body.isHoldAtLocation,
      isIgnoreZipNotFound: body.isIgnoreZipNotFound,
      isIgnoreZipStateNotMatch: body.isIgnoreZipStateNotMatch,
      isResidential: body.isResidential,
      processed: body.processed,
      isSaturdayDelivery: body.isSaturdayDelivery,
      isSaturdayPickup: body.isSaturdayPickup,
      isVerbalConfirmation: body.isVerbalConfirmation,
      isAddedHandling: body.isAddedHandling,
      ...newObjValue,
      tableName: 'm_package'
    })
    if(res) {
      data = res
      data['status'] = 200
      data['message'] = ''
    }
  }

  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
})