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"

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

  const resp: any = await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
    TrackingNo: option.tracking_number,
    //Sendcloud_Parcel_ID: option.parcel_id,
    //IsCommissioned: true,
    tableName: 'M_Inout'
  })
  if(resp) {
    data['shipment'] = resp
    data['status'] = 200
    data['message'] = ''
  }

  return data
}

const handleFunc = async (event: any) => {
  let data: any = {}
  const config = useRuntimeConfig()
  const body = await readBody(event)

  let newObjValue = {}
  if(body.shipmentId) {
    newObjValue = {...newObjValue, 
      shipment: {
        id: body.shipmentId
      }
    }
  }
  if(body.companyName) {
    newObjValue = {...newObjValue, company_name: body.companyName}
  }
  if(body.email) {
    newObjValue = {...newObjValue, email: body.email}
  }
  if(body.telephone) {
    newObjValue = {...newObjValue, telephone: body.telephone}
  }
  if(body.address2) {
    newObjValue = {...newObjValue, address_2: body.address2}
  }
  if(body.countryState) {
    newObjValue = {...newObjValue, country_state: body.countryState}
  }
  if(body.toServicePoint) {
    newObjValue = {...newObjValue, to_service_point: body.toServicePoint}
  }
  if(body.toPostNumber) {
    newObjValue = {...newObjValue, to_post_number: body.toPostNumber}
  }
  if(body.customsInvoiceNR) {
    newObjValue = {...newObjValue, customs_invoice_nr: body.customsInvoiceNR}
  }
  if(body.customsShipmentType) {
    newObjValue = {...newObjValue, customs_shipment_type: body.customsShipmentType}
  }
  if(body.weight) {
    newObjValue = {...newObjValue, weight: body.weight}
  }
  if(body.length) {
    newObjValue = {...newObjValue, length: body.length}
  }
  if(body.width) {
    newObjValue = {...newObjValue, width: body.width}
  }
  if(body.height) {
    newObjValue = {...newObjValue, height: body.height}
  }
  if(body.orderNumber) {
    newObjValue = {...newObjValue, order_number: body.orderNumber}
  }
  if(body.totalOrderValue) {
    newObjValue = {...newObjValue, total_order_value: body.totalOrderValue}
  }
  if(body.totalOrderValueCurrency) {
    newObjValue = {...newObjValue, total_order_value_currency: body.totalOrderValueCurrency}
  }
  if(body.shippingMethodCheckoutName) {
    newObjValue = {...newObjValue, shipping_method_checkout_name: body.shippingMethodCheckoutName}
  }
  /*if(body.senderAddress) {
    newObjValue = {...newObjValue, sender_address: body.senderAddress}
  }*/
  if(body.quantity) {
    newObjValue = {...newObjValue, quantity: body.quantity}
  }
  if(body.totalInsuredValue) {
    newObjValue = {...newObjValue, total_insured_value: body.totalInsuredValue}
  }

  const res: any = await sendcloudHelper('parcels', 'PUT', {
    parcel: {
      id: body.id,
      name: body.name,
      address: body.address,
      city: body.city,
      country: body.country,
      postal_code: Number(body.postalCode),
      house_number: String(body.houseNumber || ''),
      is_return: body.isReturn,
      request_label: body.requestLabel,
      apply_shipping_rules: body.applyShippingRules,
      request_label_async: body.requestLabelAsync,
      external_reference: body.inOutId,
      ...newObjValue,
    }
  })
  if(res?.parcel) {
    try {
      data = await handleInoutFunc(event, null, {
        inout_id: body.inOutId,
        tracking_number: res.parcel.tracking_number,
        parcel_id: res.parcel.id
      })
    } catch(err: any) {
      try {
        let authToken: any = await refreshTokenHelper(event)
        data = await handleInoutFunc(event, authToken, {
          inout_id: body.inOutId,
          tracking_number: res.parcel.tracking_number,
          parcel_id: res.parcel.id
        })
      } catch(error: any) {
        data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
        forceLogoutHelper(event, data)
      }
    }
    data['parcel'] = res.parcel
  } else {
    data['status'] = 500
    data['message'] = 'Parcel is not being created!'
  }

  return data
}

export default defineEventHandler(async (event) => {
  let data: any = {}

  try {
    data = await handleFunc(event)
  } catch(err: any) {
    data = errorHandlingHelper(err, err)
  }

  return data
})