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
    }}
  }
  if(body.asin) {
    newObjValue = {...newObjValue, asin: body.asin}
  }
  if(body.mpn) {
    newObjValue = {...newObjValue, mpn: body.mpn}
  }
  // 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,
    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
})