import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"

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.uomId) {
    newObjValue = {...newObjValue, C_UOM_ID: {
      id: body.uomId,
      tableName: 'C_UOM'
    }}
  }
  if(body.productCategoryId) {
    newObjValue = {...newObjValue, M_Product_Category_ID: {
      id: body.productCategoryId,
      tableName: 'M_Product_Category'
    }}
  }
  if(body.taxCategoryId) {
    newObjValue = {...newObjValue, C_TaxCategory_ID: {
      id: body.taxCategoryId,
      tableName: 'C_TaxCategory'
    }}
  }
  if(body.productTypeId) {
    newObjValue = {...newObjValue, ProductType: {
      id: body.productTypeId
    }}
  }
  if(body.attributeSetId) {
    newObjValue = {...newObjValue, M_AttributeSet_ID: {
      id: body.attributeSetId,
      tableName: 'M_AttributeSet'
    }}
  }
  if(body.attributeSetInstanceId) {
    newObjValue = {...newObjValue, M_AttributeSetInstance_ID: {
      id: body.attributeSetInstanceId,
      tableName: 'M_AttributeSetInstance'
    }}
  }
  if(body.revenueRecognitionId) {
    newObjValue = {...newObjValue, C_RevenueRecognition_ID: {
      id: body.revenueRecognitionId,
      tableName: 'C_RevenueRecognition'
    }}
  }
  if(body.salesRepId) {
    newObjValue = {...newObjValue, SalesRep_ID: {
      id: body.salesRepId,
      tableName: 'AD_User'
    }}
  }
  if(body.mailTextId) {
    newObjValue = {...newObjValue, R_MailText_ID: {
      id: body.mailTextId,
      tableName: 'R_Mailtext'
    }}
  }
  if(body.organizationId) {
    newObjValue = {...newObjValue, AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    }}
  }
  if(body.labelPrinterId) {
    newObjValue = {...newObjValue, labelprinter: {
      id: body.labelPrinterId
    }}
  } else if(body.labelPrinterId === '' || body.labelPrinterId === null) {
    newObjValue = {...newObjValue, labelprinter: 0}
  }
  if(body.labelPrinterRmaId) {
    newObjValue = {...newObjValue, labelprinter_rma: {
      id: body.labelPrinterRmaId
    }}
  } else if(body.labelPrinterRmaId === '' || body.labelPrinterRmaId === null) {
    newObjValue = {...newObjValue, labelprinter_rma: 0}
  }
  if(body.paketTypeId) {
    newObjValue = {...newObjValue, M_Paket_Type_ID: {
      id: body.paketTypeId,
      tableName: 'M_Product'
    }}
  } else if(body.paketTypeId === '' || body.paketTypeId === null) {
    newObjValue = {...newObjValue, M_Paket_Type_ID: 0}
  }
  if(body.asin) {
    newObjValue = {...newObjValue, asin: body.asin}
  }
  if(body.mpn) {
    newObjValue = {...newObjValue, mpn: body.mpn}
  }
  if(body.pickListCode !== undefined) {
    newObjValue = {...newObjValue, pickListCode: body.pickListCode}
  }
  if(body.jfsku !== undefined) {
    newObjValue = {...newObjValue, jfsku: body.jfsku}
  }
  if(body.fnsku !== undefined) {
    newObjValue = {...newObjValue, fnsku: body.fnsku}
  }
  if(body.customFulfillmentPrice !== undefined) {
    newObjValue = {...newObjValue, CustomFulfillmentPrice: body.customFulfillmentPrice}
  }
  if(body.isCustomFulfillmentPrice !== undefined) {
    newObjValue = {...newObjValue, isCustomFulfillmentPrice: body.isCustomFulfillmentPrice}
  }
  if(body.fulfillmentProductPricingRulesId) {
    newObjValue = {...newObjValue, CUST_FulfillmentProductPricingRules_ID: {
      id: body.fulfillmentProductPricingRulesId,
      tableName: 'CUST_FulfillmentProductPricingRules'
    }}
  } else if(body.fulfillmentProductPricingRulesId === '' || body.fulfillmentProductPricingRulesId === null) {
    newObjValue = {...newObjValue, CUST_FulfillmentProductPricingRules_ID: 0}
  }
  if(body.originCountryId) {
    newObjValue = {...newObjValue, C_Country_ID: {
      id: body.originCountryId,
      tableName: 'C_Country'
    }}
  } else if(body.originCountryId === '' || body.originCountryId === null) {
    newObjValue = {...newObjValue, C_Country_ID: 0}
  }
  if(body.taricCode !== undefined) {
    newObjValue = {...newObjValue, taricCode: body.taricCode}
  }
  // Custom columns (exact iDempiere ColumnName casing) — only sent when the caller
  // provides them, so older callers/envs without the columns stay unaffected.
  if(body.upc2 !== undefined) {
    newObjValue = {...newObjValue, UPC2: body.upc2}
  }
  if(body.netWeight !== undefined) {
    newObjValue = {...newObjValue, netWeight: body.netWeight}
  }
  if(body.isEnabledBom !== undefined) {
    newObjValue = {...newObjValue, isEnabledBom: body.isEnabledBom}
  }
  if(body.isAutoCommission !== undefined) {
    newObjValue = {...newObjValue, isAutoCommission: body.isAutoCommission}
  }
  // Always include physical dimensions if provided
  if(body.volume !== undefined) {
    newObjValue = {...newObjValue, volume: body.volume}
  }
  if(body.width !== undefined) {
    newObjValue = {...newObjValue, width: body.width}
  }
  if(body.length !== undefined) {
    newObjValue = {...newObjValue, length: body.length}
  }
  if(body.height !== undefined) {
    newObjValue = {...newObjValue, height: body.height}
  }

  const res: any = await event.context.fetch('models/m_product/'+body.id, 'PUT', token, {
    isActive: body.isActive,
    name: body.name,
    SKU: body.sku,
    UPC: body.upc,
    value: body.value,
    versionNo: body.versionNo,
    description: body.description,
    help: body.help,
    documentNote: body.documentNote,
    isSummary: body.isSummary,
    isStocked: body.isStocked,
    isPurchased: body.isPurchased,
    isSold: body.isSold,
    weight: body.weight,
    discontinued: body.discontinued,
    isBOM: body.isBOM,
    isInvoicePrintDetails: body.isInvoicePrintDetails,
    isPickListPrintDetails: body.isPickListPrintDetails,
    guaranteeDaysMin: body.guaranteeDaysMin,
    isWebStoreFeatured: body.isWebStoreFeatured,
    isSelfService: body.isSelfService,
    isDropShip: body.isDropShip,
    isExcludeAutoDelivery: body.isExcludeAutoDelivery,
    unitsPerPack: body.unitsPerPack,
    lowLevel: body.lowLevel,
    isKanban: body.isKanban,
    isManufactured: body.isManufactured,
    isPhantom: body.isPhantom,
    isOwnBox: body.isOwnBox,
    isAutoProduce: body.isAutoProduce,
    CompletedAllMarketplaceData: body.completedAllMarketplaceData,
    shelfWidth: body.shelfWidth,
    shelfHeight: body.shelfHeight,
    shelfDepth: body.shelfDepth,
    unitsPerPallet: body.unitsPerPallet,
    classification: body.classification,
    customsTariffNumber: body.customsTariffNumber,
    group1: body.group1,
    group2: body.group2,
    ...newObjValue,
    tableName: 'M_Product'
  })
  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) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})