import refreshTokenHelper from "../../../utils/refreshTokenHelper"
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.warehouseId) {
    newObjValue = {...newObjValue, 
      M_Warehouse_ID: {
        id: body.warehouseId,
        tableName: 'M_Warehouse'
      }
    }
  }
  if(body.priceListId) {
    newObjValue = {...newObjValue, 
      M_PriceList_ID: {
        id: body.priceListId,
        tableName: 'M_PriceList'
      }
    }
  }
  if(body.priceListVersionId) {
    newObjValue = {...newObjValue, 
      M_PriceList_Version_ID: {
        id: body.priceListVersionId,
        tableName: 'M_PriceList_Version'
      }
    }
  }
  if(body.plentyOneOrderFilterCode) {
    newObjValue = {...newObjValue, plentyone_orderfilter_code: body.plentyOneOrderFilterCode }
  }
  if(body.plentyOneOrderImportCode) {
    newObjValue = {...newObjValue, plentyone_orderimport_code: body.plentyOneOrderImportCode }
  }
  if(body.plentyOneOrderCommissionCode) {
    newObjValue = {...newObjValue, plentyone_ordercommission_code: body.plentyOneOrderCommissionCode }
  }
  if(body.plentyOneWarehouseId) {
    newObjValue = {...newObjValue, PlentyOne_Warehouse_ID: body.plentyOneWarehouseId }
  }
  if(body.DHLUseCustom && body.DHLURL) {
    newObjValue = {
      ...newObjValue, 
      DHLURL: body.DHLURL,
      DHLKEY: body.DHLKey,
      DHLSECRET: body.DHLSecret,
      DHLUSER: body.DHLUser,
      DHLPASS: body.DHLPass,
      DHL_USE_CUSTOM: body.DHLUseCustom,
      dhl_billing_number_de: body.DHLBillingNumberDE,
      dhl_billing_number_int: body.DHLBillingNumberINT
    }
  } else {
    newObjValue = {
      ...newObjValue, 
      DHL_USE_CUSTOM: body.DHLUseCustom ?? false,
    }
  }
  if(body.shipperCustom1Id) {
    newObjValue = {...newObjValue, 
      M_Shipper_Custom1_ID: {
        id: body.shipperCustom1Id,
        tableName: 'M_Shipper'
      }
    }
  }
  if(body.shipperCustom2Id) {
    newObjValue = {...newObjValue, 
      M_Shipper_Custom2_ID: {
        id: body.shipperCustom2Id,
        tableName: 'M_Shipper'
      }
    }
  }
  if(body.jtlMerchantId) {
    newObjValue = {
      ...newObjValue, 
      jtl_merchantID: body.jtlMerchantId
    }
  }

  const res: any = await fetchHelper(event, 'models/c_ordersource/'+body.id, 'PUT', token, {
    isActive: body.isActive,
    name: body.name,
    value: body.value,
    description: body.description,
    marketplace: body.marketplaceId,
    marketplace_url: body.marketplaceUrl,
    marketplace_key: body.marketplaceKey,
    marketplace_secret: body.marketplaceSecret,
    marketplace_token: body.marketplaceToken,
    starting_order_id: body.startingOrderId,
    starting_order_date: body.startingOrderDate,
    syncProductToIdempiere: body.syncProductToIdempiere ?? false,
    syncProductFromIdempiere: body.syncProductFromIdempiere ?? false,
    syncOrderToIdempiere: body.syncOrderToIdempiere ?? false,
    syncOrderFromIdempiere: body.syncOrderFromIdempiere ?? false,
    syncShipmentToIdempiere: body.syncShipmentToIdempiere ?? false,
    syncShipmentFromIdempiere: body.syncShipmentFromIdempiere ?? false,
    isExcludetrackingmail: body.isExcludetrackingmail ?? false,
    IsCustomTrackingMail: body.isCustomTrackingMail ?? false,
    isSentCustomTrackingMail: body.isSentCustomTrackingMail ?? false,
    isBomConvert: body.isBoMConvert ?? false,
    isTaxIncluded: body.isTaxIncluded ?? false,
    External_Shipping_Profile_1: body.externalShippingProfile1 ?? false,
    External_Shipping_Profile_2: body.externalShippingProfile2 ?? false,
    remove_article_string: body.removeArticleString ?? '',
    help: body.help,
    ...newObjValue,
    tableName: 'c_ordersource'
  })
  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)
      if([401, 402, 403, 407].includes(Number(data.status))) {
        //@ts-ignore
        setCookie(event, 'user', null)
      }
    }
  }

  return data
})