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"

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,
    Sendcloud_Parcel_ID: 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)
      }
    }
    
    const res: any = await sendcloudHelper(`parcels/${body.id}/cancel`, 'POST', null)
    if(res) {
      data['parcel'] = res
    }
  } catch(error: any) {
    data['status'] = 500
    data['message'] = error?.message ?? 'Parcel is not being properly cancelled!'
  }

  return data
})