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)

  // Only include changed fields in the update payload
  let updatePayload: any = {}

  // Helper function to add field if it exists in body
  const addIfChanged = (bodyKey: string, apiKey: string, value?: any) => {
    if (body.hasOwnProperty(bodyKey)) {
      updatePayload[apiKey] = value !== undefined ? value : body[bodyKey]
    }
  }

  // Helper for reference fields (objects with id)
  const addRefIfChanged = (bodyKey: string, apiKey: string, tableName?: string) => {
    if (body.hasOwnProperty(bodyKey) && body[bodyKey]) {
      const ref: any = { id: body[bodyKey] }
      if (tableName) ref.tableName = tableName
      updatePayload[apiKey] = ref
    }
  }

  // Basic fields
  addIfChanged('isActive', 'isActive')
  addIfChanged('name', 'name')
  addIfChanged('value', 'value')
  addIfChanged('description', 'Description')
  addIfChanged('help', 'Help')
  // SHOPWARE_* and marketplace_* are SEPARATE columns on c_ordersource; the Amazon/eBay
  // API consumers read marketplace_*, so both pairs must be written to stay in sync.
  addIfChanged('marketplaceUrl', 'SHOPWARE_URL')
  addIfChanged('marketplaceUrl', 'marketplace_url')
  addIfChanged('marketplaceKey', 'SHOPWARE_KEY')
  addIfChanged('marketplaceKey', 'marketplace_key')
  addIfChanged('marketplaceSecret', 'SHOPWARE_SECRET')
  addIfChanged('marketplaceSecret', 'marketplace_secret')
  addIfChanged('marketplaceToken', 'marketplace_token')
  addIfChanged('startingOrderId', 'starting_order_id')
  addIfChanged('startingOrderDate', 'starting_order_date')
  addIfChanged('removeArticleString', 'remove_article_string')

  // Sync flags
  addIfChanged('syncProductToIdempiere', 'syncProductToIdempiere')
  addIfChanged('syncProductFromIdempiere', 'syncProductFromIdempiere')
  addIfChanged('syncOrderToIdempiere', 'syncOrderToIdempiere')
  addIfChanged('syncOrderFromIdempiere', 'syncOrderFromIdempiere')
  addIfChanged('syncShipmentToIdempiere', 'syncShipmentToIdempiere')
  addIfChanged('syncShipmentFromIdempiere', 'syncShipmentFromIdempiere')

  // Boolean flags
  addIfChanged('isExcludetrackingmail', 'isExcludetrackingmail')
  addIfChanged('isCustomTrackingMail', 'IsCustomTrackingMail')
  addIfChanged('isSentCustomTrackingMail', 'isSentCustomTrackingMail')
  addIfChanged('isBoMConvert', 'isBomConvert')
  addIfChanged('isJtlBomSkip', 'isJtlBomSkip')
  addIfChanged('includeBomSync', 'includeBomSync')
  addIfChanged('isTaxIncluded', 'IsTaxIncluded')
  addIfChanged('isShopware6', 'isShopware6')
  addIfChanged('isWebshopToIdempiere', 'isWebshopToIdempiere')
  addIfChanged('isIdempiereToWebshop', 'isIdempiereToWebshop')
  addIfChanged('isSkipConfirmation', 'isSkipCOnfirmation')
  addIfChanged('isShopifyUpdatedMin', 'is_shopify_updated_min')
  addIfChanged('isCheckShopifyFulfillmentService', 'isCheckShopifyFulfillmentService')
  addIfChanged('isSyncQtyOnHandOnCommission', 'isSyncQtyOnHandOnCommission')
  addIfChanged('isSyncProductQtySchedule', 'isSyncProductQtySchedule')

  // PlentyOne fields
  addIfChanged('plentyOneOrderFilterCode', 'plentyone_orderfilter_code')
  addIfChanged('plentyOneOrderImportCode', 'plentyone_orderimport_code')
  addIfChanged('plentyOneOrderCommissionCode', 'plentyone_ordercommission_code')
  addIfChanged('plentyOneWarehouseId', 'PlentyOne_Warehouse_ID')

  // External shipping profiles
  addIfChanged('externalShippingProfile1', 'External_Shipping_Profile_1')
  addIfChanged('externalShippingProfile2', 'External_Shipping_Profile_2')
  addIfChanged('externalShippingProfile3', 'External_Shipping_Profile_3')
  addIfChanged('externalShippingProfile4', 'External_Shipping_Profile_4')
  addIfChanged('externalShippingProfile5', 'External_Shipping_Profile_5')
  addIfChanged('externalShippingProfile6', 'External_Shipping_Profile_6')
  addIfChanged('externalShippingProfile7', 'External_Shipping_Profile_7')
  addIfChanged('externalShippingProfile8', 'External_Shipping_Profile_8')

  // DHL fields — each persists independently (the edit page sends changed fields
  // only, so gating on the toggle/URL being present would drop single-field edits)
  addIfChanged('DHLURL', 'DHLURL')
  addIfChanged('DHLKey', 'DHLKEY')
  addIfChanged('DHLSecret', 'DHLSECRET')
  addIfChanged('DHLUser', 'DHLUSER')
  addIfChanged('DHLPass', 'DHLPASS')
  addIfChanged('DHLUseCustom', 'DHL_USE_CUSTOM')
  addIfChanged('DHLBillingNumberDE', 'dhl_billing_number_de')
  addIfChanged('DHLBillingNumberINT', 'dhl_billing_number_int')

  // DPD fields — same treatment, independent from DHL
  addIfChanged('DPDURL', 'DPDURL')
  addIfChanged('DPDDelisId', 'DPDDELISID')
  addIfChanged('DPDPassword', 'DPDPASSWORD')
  addIfChanged('DPDCustomerNumber', 'DPDCUSTOMERNUMBER')
  addIfChanged('DPDDepot', 'DPDDEPOT')
  addIfChanged('DPDUseCustom', 'DPD_USE_CUSTOM')

  // Marketplace-specific fields
  addIfChanged('jtlMerchantId', 'jtl_merchantID')
  addIfChanged('amazonMerchantId', 'amazon_merchant_id')
  addIfChanged('ebayEnvironment', 'ebay_environment')
  addIfChanged('ebayRuName', 'ebay_ru_name')

  // New fields
  addIfChanged('isSyncSelectedArticlesOnly', 'isSyncSelectedArticlesOnly')
  addIfChanged('selectedArticlesSync', 'selectedArticlesSync')
  addIfChanged('saveSkuBack', 'save_sku_back')
  addIfChanged('shopifyIgnoreLocation', 'shopify_ignore_location')
  addIfChanged('shopifyLocationId', 'shopify_location_id')
  addIfChanged('isAmazonOrderReport', 'is_amazon_order_report')
  addIfChanged('isCheckoutNoteKeepOrderOpen', 'isCheckoutNoteKeepOrderOpen')

  // Reference fields (with id objects)
  addRefIfChanged('organizationId', 'AD_Org_ID', 'AD_Org')
  addRefIfChanged('warehouseId', 'M_Warehouse_ID', 'M_Warehouse')
  addRefIfChanged('marketplaceId', 'Marketplace')
  addRefIfChanged('priceListId', 'M_PriceList_ID', 'M_PriceList')
  addRefIfChanged('priceListVersionId', 'M_PriceList_Version_ID', 'M_PriceList_Version')
  addRefIfChanged('priceListProductId', 'M_PriceList_Product_ID', 'M_PriceList')
  addRefIfChanged('priceListVersionProductId', 'M_PriceList_Version_Product_ID', 'M_PriceList_Version')
  addRefIfChanged('invoiceRuleId', 'InvoiceRule')

  // Shipper custom references
  addRefIfChanged('shipperCustom1Id', 'M_Shipper_Custom1_ID', 'M_Shipper')
  addRefIfChanged('shipperCustom2Id', 'M_Shipper_Custom2_ID', 'M_Shipper')
  addRefIfChanged('shipperCustom3Id', 'M_Shipper_Custom3_ID', 'M_Shipper')
  addRefIfChanged('shipperCustom4Id', 'M_Shipper_Custom4_ID', 'M_Shipper')
  addRefIfChanged('shipperCustom5Id', 'M_Shipper_Custom5_ID', 'M_Shipper')
  addRefIfChanged('shipperCustom6Id', 'M_Shipper_Custom6_ID', 'M_Shipper')
  addRefIfChanged('shipperCustom7Id', 'M_Shipper_Custom7_ID', 'M_Shipper')
  addRefIfChanged('shipperCustom8Id', 'M_Shipper_Custom8_ID', 'M_Shipper')

  const res: any = await fetchHelper(event, 'models/c_ordersource/'+body.id, 'PUT', token, {
    ...updatePayload,
    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
})
