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.organizationId) {
    newObjValue = {...newObjValue, AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    }}
  }
  if(body.freightCategoryId) {
    newObjValue = {...newObjValue, 
      M_FreightCategory_ID: {
        id: body.freightCategoryId,
        tableName: 'M_FreightCategory'
      }
    }
  }
  if(body.currencyId) {
    newObjValue = {...newObjValue, 
      C_Currency_ID: {
        id: body.currencyId,
        tableName: 'C_Currency'
      }
    }
  }
  if(body.countryId) {
    newObjValue = {...newObjValue, 
      C_Country_ID: {
        id: body.countryId,
        tableName: 'C_Country'
      }
    }
  }
  if(body.toCountryId) {
    newObjValue = {...newObjValue, 
      To_Country_ID: {
        id: body.toCountryId,
        tableName: 'C_Country'
      }
    }
  }
  if(body.regionId) {
    newObjValue = {...newObjValue, 
      C_Region_ID: {
        id: body.regionId,
        tableName: 'C_Region'
      }
    }
  }
  if(body.toRegionId) {
    newObjValue = {...newObjValue, 
      To_Region_ID: {
        id: body.toRegionId,
        tableName: 'C_Region'
      }
    }
  }
  if(body.shipperId) {
    newObjValue = {...newObjValue, 
      M_Shipper_ID: {
        id: body.shipperId,
        tableName: 'M_Shipper'
      }
    }
  }

  const res: any = await fetchHelper(event, 'models/m_freight/'+body.id, 'PUT',token, {
    isActive: body.isActive,
    freightAmt: body.freightAmt,
    validFrom: body.validFrom,
    maxWeight: body.maxWeight,
    maxDimension: body.maxDimension,
    ...newObjValue,
    tableName: 'm_freight'
  })
  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
})