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 { invalidateDhlMainCredential } from "../../../utils/dhlMainCredential"

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)

  // Only send what the caller provides — the grid inline-edit sends just name/isActive,
  // the edit page sends the full field set.
  let newObjValue: any = {}
  if(body.organizationId) {
    newObjValue = {...newObjValue, AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    }}
  }
  if(body.shippingProcessorId) {
    newObjValue = {...newObjValue, M_ShippingProcessor_ID: {
      id: body.shippingProcessorId,
      tableName: 'M_ShippingProcessor'
    }}
  }
  if(body.shipperCfgId) {
    newObjValue = {...newObjValue, M_ShipperCfg_ID: {
      id: body.shipperCfgId,
      tableName: 'M_ShipperCfg'
    }}
  }
  if(body.partnerId) {
    newObjValue = {...newObjValue, C_BPartner_ID: {
      id: body.partnerId,
      tableName: 'C_BPartner'
    }}
  }
  if(body.isReadTrackingCommission !== undefined) {
    newObjValue = {...newObjValue, isReadTrackingCommission: body.isReadTrackingCommission === true}
  }
  if(body.readTrackingLength !== undefined) {
    newObjValue = {...newObjValue, readtrackinglength: Number(body.readTrackingLength) || 0}
  }
  if(body.isAttachmentRequired !== undefined) {
    newObjValue = {...newObjValue, isAttachmentRequired: body.isAttachmentRequired === true}
  }
  if(body.isPrintDINA4 !== undefined) {
    newObjValue = {...newObjValue, isPrintDINA4: body.isPrintDINA4 === true}
  }
  if(body.isPickupTrackingNumberMandatory !== undefined) {
    newObjValue = {...newObjValue, isPickupTrackingNumberMandatory: body.isPickupTrackingNumberMandatory === true}
  }
  if(body.isAmazonFba !== undefined) {
    newObjValue = {...newObjValue, isAmazonFba: body.isAmazonFba === true}
  }
  if(body.isNoShippingAccounting !== undefined) {
    newObjValue = {...newObjValue, isNoShippingAccounting: body.isNoShippingAccounting === true}
  }
  // Central DHL account (credentials + billing numbers) — read at runtime by
  // server/utils/dhlMainCredential.ts. Sent only when present in the body;
  // '' clears the column. Column-name casing matches the iDempiere columns
  // (same convention as settings/order-sources/update.put.ts).
  if(body.dhlUrl !== undefined) {
    newObjValue = {...newObjValue, DHLURL: body.dhlUrl}
  }
  if(body.dhlKey !== undefined) {
    newObjValue = {...newObjValue, DHLKEY: body.dhlKey}
  }
  if(body.dhlSecret !== undefined) {
    newObjValue = {...newObjValue, DHLSECRET: body.dhlSecret}
  }
  if(body.dhlUser !== undefined) {
    newObjValue = {...newObjValue, DHLUSER: body.dhlUser}
  }
  if(body.dhlPass !== undefined) {
    newObjValue = {...newObjValue, DHLPASS: body.dhlPass}
  }
  if(body.dhlBillingNumberDe !== undefined) {
    newObjValue = {...newObjValue, dhl_billing_number_de: body.dhlBillingNumberDe}
  }
  if(body.dhlBillingNumberInt !== undefined) {
    newObjValue = {...newObjValue, dhl_billing_number_int: body.dhlBillingNumberInt}
  }
  if(body.dhlBillingNumberKp !== undefined) {
    newObjValue = {...newObjValue, dhl_billing_number_kp: body.dhlBillingNumberKp}
  }
  if(body.dhlBillingNumberWpInt !== undefined) {
    newObjValue = {...newObjValue, dhl_billing_number_wp_int: body.dhlBillingNumberWpInt}
  }
  if(body.dhlBillingNumberRetoure !== undefined) {
    newObjValue = {...newObjValue, dhl_billing_number_retoure: body.dhlBillingNumberRetoure}
  }

  const res: any = await fetchHelper(event, 'models/m_shipper/'+body.id, 'PUT', token, {
    isActive: body.isActive,
    name: body.name,
    ...newObjValue,
    tableName: 'M_Shipper'
  })
  if(res) {
    data = res
    data['status'] = 200
    data['message'] = ''
    // A shipper save may have changed the central DHL account — refresh on next use.
    invalidateDhlMainCredential()
  }

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