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.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.priceListProductId) {
    newObjValue = {...newObjValue,
      M_PriceList_Product_ID: {
        id: body.priceListProductId,
        tableName: 'M_PriceList'
      }
    }
  }
  if(body.priceListVersionProductId) {
    newObjValue = {...newObjValue,
      M_PriceList_Version_Product_ID: {
        id: body.priceListVersionProductId,
        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 }
  }
  // DHL fields — persist whatever was provided (gating on toggle+URL dropped
  // partially filled credentials); the toggle is always written explicitly
  newObjValue = {
    ...newObjValue,
    ...(body.DHLURL ? { DHLURL: body.DHLURL } : {}),
    ...(body.DHLKey ? { DHLKEY: body.DHLKey } : {}),
    ...(body.DHLSecret ? { DHLSECRET: body.DHLSecret } : {}),
    ...(body.DHLUser ? { DHLUSER: body.DHLUser } : {}),
    ...(body.DHLPass ? { DHLPASS: body.DHLPass } : {}),
    ...(body.DHLBillingNumberDE ? { dhl_billing_number_de: body.DHLBillingNumberDE } : {}),
    ...(body.DHLBillingNumberINT ? { dhl_billing_number_int: body.DHLBillingNumberINT } : {}),
    DHL_USE_CUSTOM: body.DHLUseCustom ?? false
  }
  // DPD fields — same treatment
  newObjValue = {
    ...newObjValue,
    ...(body.DPDURL ? { DPDURL: body.DPDURL } : {}),
    ...(body.DPDDelisId ? { DPDDELISID: body.DPDDelisId } : {}),
    ...(body.DPDPassword ? { DPDPASSWORD: body.DPDPassword } : {}),
    ...(body.DPDCustomerNumber ? { DPDCUSTOMERNUMBER: body.DPDCustomerNumber } : {}),
    ...(body.DPDDepot ? { DPDDEPOT: body.DPDDepot } : {}),
    DPD_USE_CUSTOM: body.DPDUseCustom ?? 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
    }
  }
  if(body.ebayEnvironment) {
    newObjValue = {
      ...newObjValue,
      ebay_environment: body.ebayEnvironment,
      ebay_ru_name: body.ebayRuName || ''
    }
  }
  if(body.invoiceRuleId) {
    newObjValue = {
      ...newObjValue,
      InvoiceRule: {
        id: body.invoiceRuleId
      }
    }
  }
  if(body.hasOwnProperty('isSyncSelectedArticlesOnly')) {
    newObjValue = { ...newObjValue, isSyncSelectedArticlesOnly: body.isSyncSelectedArticlesOnly ?? false }
  }
  if(body.selectedArticlesSync) {
    newObjValue = { ...newObjValue, selectedArticlesSync: body.selectedArticlesSync }
  }
  if(body.hasOwnProperty('saveSkuBack')) {
    newObjValue = { ...newObjValue, save_sku_back: body.saveSkuBack ?? false }
  }
  if(body.hasOwnProperty('shopifyIgnoreLocation')) {
    newObjValue = { ...newObjValue, shopify_ignore_location: body.shopifyIgnoreLocation ?? false }
  }
  if(body.shopifyLocationId) {
    newObjValue = { ...newObjValue, shopify_location_id: body.shopifyLocationId }
  }
  if(body.hasOwnProperty('isAmazonOrderReport')) {
    newObjValue = { ...newObjValue, is_amazon_order_report: body.isAmazonOrderReport ?? false }
  }
  if(body.hasOwnProperty('isCheckoutNoteKeepOrderOpen')) {
    newObjValue = { ...newObjValue, isCheckoutNoteKeepOrderOpen: body.isCheckoutNoteKeepOrderOpen ?? false }
  }

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