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)

  let newObjValue = {}
  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'
    }}
  }
  // Custom flags: only send the non-default value — DB columns default to 'N'.
  if(body.isReadTrackingCommission === true) {
    newObjValue = {...newObjValue, isReadTrackingCommission: true}
  }
  if(Number(body.readTrackingLength) > 0) {
    newObjValue = {...newObjValue, readtrackinglength: Number(body.readTrackingLength)}
  }
  if(body.isAttachmentRequired === true) {
    newObjValue = {...newObjValue, isAttachmentRequired: true}
  }
  if(body.isPrintDINA4 === true) {
    newObjValue = {...newObjValue, isPrintDINA4: true}
  }
  if(body.isPickupTrackingNumberMandatory === true) {
    newObjValue = {...newObjValue, isPickupTrackingNumberMandatory: true}
  }
  if(body.isAmazonFba === true) {
    newObjValue = {...newObjValue, isAmazonFba: true}
  }
  if(body.isNoShippingAccounting === true) {
    newObjValue = {...newObjValue, isNoShippingAccounting: true}
  }
  // Central DHL account fields — only sent when non-empty (DB columns are nullable;
  // keeps creation working even if a column is missing in iDempiere).
  if(body.dhlUrl) {
    newObjValue = {...newObjValue, DHLURL: body.dhlUrl}
  }
  if(body.dhlKey) {
    newObjValue = {...newObjValue, DHLKEY: body.dhlKey}
  }
  if(body.dhlSecret) {
    newObjValue = {...newObjValue, DHLSECRET: body.dhlSecret}
  }
  if(body.dhlUser) {
    newObjValue = {...newObjValue, DHLUSER: body.dhlUser}
  }
  if(body.dhlPass) {
    newObjValue = {...newObjValue, DHLPASS: body.dhlPass}
  }
  if(body.dhlBillingNumberDe) {
    newObjValue = {...newObjValue, dhl_billing_number_de: body.dhlBillingNumberDe}
  }
  if(body.dhlBillingNumberInt) {
    newObjValue = {...newObjValue, dhl_billing_number_int: body.dhlBillingNumberInt}
  }
  if(body.dhlBillingNumberKp) {
    newObjValue = {...newObjValue, dhl_billing_number_kp: body.dhlBillingNumberKp}
  }
  if(body.dhlBillingNumberWpInt) {
    newObjValue = {...newObjValue, dhl_billing_number_wp_int: body.dhlBillingNumberWpInt}
  }
  if(body.dhlBillingNumberRetoure) {
    newObjValue = {...newObjValue, dhl_billing_number_retoure: body.dhlBillingNumberRetoure}
  }

  const res: any = await fetchHelper(event, 'models/m_shipper', 'POST', token, {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    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
})