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.deliveryRuleId) {
    newObjValue = {...newObjValue, DeliveryRule: {
      id: body.deliveryRuleId
    }}
  }
  if(body.deliveryViaRuleId) {
    newObjValue = {...newObjValue, DeliveryViaRule: {
      id: body.deliveryViaRuleId
    }}
  }
  if(body.invoiceScheduleId) {
    newObjValue = {...newObjValue, C_InvoiceSchedule_ID: {
      id: body.invoiceScheduleId,
      tableName: 'C_InvoiceSchedule'
    }}
  }
  if(body.greetingId) {
    newObjValue = {...newObjValue, C_Greeting_ID: {
      id: body.greetingId,
      tableName: 'C_Greeting'
    }}
  }
  if(body.printFormatId) {
    newObjValue = {...newObjValue, Invoice_PrintFormat_ID: {
      id: body.printFormatId,
      tableName: 'AD_Printformat'
    }}
  }
  if(body.salesRepId) {
    newObjValue = {...newObjValue, SalesRep_ID: {
      id: body.salesRepId
    }}
  }
  if(body.invoiceRuleId) {
    newObjValue = {...newObjValue, InvoiceRule: {
      id: body.invoiceRuleId
    }}
  }
  if(body.paymentRuleId) {
    newObjValue = {...newObjValue, PaymentRule: {
      id: body.paymentRuleId
    }}
  }
  if(body.paymentRulePOId) {
    newObjValue = {...newObjValue, PaymentRulePO: {
      id: body.paymentRulePOId
    }}
  }
  if(body.soCreditStatusId) {
    newObjValue = {...newObjValue, SOCreditStatus: {
      id: body.soCreditStatusId
    }}
  }
  if(body.partnerGroupId) {
    newObjValue = {...newObjValue, C_BP_Group_ID: {
      id: body.partnerGroupId,
      tableName: 'C_BP_Group'
    }}
  }
  if(body.priceListId) {
    newObjValue = {...newObjValue, M_PriceList_ID: {
      id: body.priceListId,
      tableName: 'M_PriceList'
    }}
  }
  if(body.poPriceListId) {
    newObjValue = {...newObjValue, PO_PriceList_ID: {
      id: body.poPriceListId,
      tableName: 'M_PriceList'
    }}
  }
  if(body.discountSchemaId) {
    newObjValue = {...newObjValue, M_DiscountSchema_ID: {
      id: body.discountSchemaId,
      tableName: 'M_PriceList'
    }}
  }
  if(body.poDiscountSchemaId) {
    newObjValue = {...newObjValue, PO_DiscountSchema_ID: {
      id: body.poDiscountSchemaId,
      tableName: 'M_PriceList'
    }}
  }
  if(body.paymentTermId) {
    newObjValue = {...newObjValue, C_PaymentTerm_ID: {
      id: body.paymentTermId,
      tableName: 'C_PaymentTerm'
    }}
  }
  if(body.poPaymentTermId) {
    newObjValue = {...newObjValue, PO_PaymentTerm_ID: {
      id: body.poPaymentTermId,
      tableName: 'C_PaymentTerm'
    }}
  }
  if(body.dunningId) {
    newObjValue = {...newObjValue, C_Dunning_ID: {
      id: body.dunningId,
      tableName: 'C_Dunning'
    }}
  }
  if(body.languageId) {
    newObjValue = {...newObjValue, AD_Language: {
      id: body.languageId,
      tableName: 'AD_Language'
    }}
  }
  /*if(body.organizationId) {
    newObjValue = {...newObjValue, 
      AD_Org_ID: {
        id: body.organizationId,
        tableName: 'AD_Org'
      }
    }
  }*/
  if(body.EMail) {
    newObjValue = {...newObjValue, EMail: body.EMail}
  }
  if(new Boolean(body.isFulfillmentCustomer)) {
    newObjValue = {...newObjValue, isFulfillmentCustomer: body.isFulfillmentCustomer}
  }
  if(body.fulfillmentOrderBaseprice) {
    newObjValue = {...newObjValue, fulfillment_order_baseprice: body.fulfillmentOrderBaseprice}
  }
  if(body.fulfillmentOrderPickprice) {
    newObjValue = {...newObjValue, fulfillment_order_pickprice: body.fulfillmentOrderPickprice}
  }
  if(body.fulfillmentOrderQtyPickfree) {
    newObjValue = {...newObjValue, fulfillment_order_qty_pickfree: body.fulfillmentOrderQtyPickfree}
  }
  if(body.fulfillmentOrderBaseprice2) {
    newObjValue = {...newObjValue, fulfillment_order_baseprice_2: body.fulfillmentOrderBaseprice2}
  }
  if(body.fulfillmentOrderBaseprice3) {
    newObjValue = {...newObjValue, fulfillment_order_baseprice_3: body.fulfillmentOrderBaseprice3}
  }
  if(body.fulfillmentOrderReturnBaseprice) {
    newObjValue = {...newObjValue, fulfillment_order_return_baseprice: body.fulfillmentOrderReturnBaseprice}
  }
  if(body.fulfillmentOrderReturnPickprice) {
    newObjValue = {...newObjValue, fulfillment_order_return_pickprice: body.fulfillmentOrderReturnPickprice}
  }
  if(new Boolean(body.isAccountLogShip)) {
    newObjValue = {...newObjValue, isAccountLogShip: body.isAccountLogShip}
  }
  if(new Boolean(body.isAccountingWarehouseVolume)) {
    newObjValue = {...newObjValue, isAccountingWarehouseVolume: body.isAccountingWarehouseVolume}
  }
  if(body.logshipmonthlyfee) {
    newObjValue = {...newObjValue, logshipmonthlyfee: body.logshipmonthlyfee}
  }
  if(body.volumeqm3price) {
    newObjValue = {...newObjValue, volumeqm3price: body.volumeqm3price}
  }
  if(body.accoutingwarehouserentstarts) {
    newObjValue = {...newObjValue, accoutingwarehouserentstarts: body.accoutingwarehouserentstarts}
  }

  const res: any = await event.context.fetch('models/c_bpartner/'+body.id, 'PUT', token, {
    isActive: body.isActive,
    name: body.name,
    name2: body.name2,
    value: body.value,
    description: body.description,
    salesVolume: body.salesVolume,
    numberEmployees: body.numberEmployees,
    isSummary: body.isSummary,
    isVendor: body.isVendor,
    isCustomer: body.isCustomer,
    isProspect: body.isProspect,
    SO_CreditLimit: body.soCreditLimit,
    SO_CreditUsed: body.soCreditUsed,
    acqusitionCost: body.acqusitionCost,
    potentialLifeTimeValue: body.potentialLifeTimeValue,
    actualLifeTimeValue: body.actualLifeTimeValue,
    shareOfCustomer: body.shareOfCustomer,
    isEmployee: body.isEmployee,
    isSalesRep: body.isSalesRep,
    isOneTime: body.isOneTime,
    isTaxExempt: body.isTaxExempt,
    isDiscountPrinted: body.isDiscountPrinted,
    sendEMail: body.sendEMail,
    totalOpenBalance: body.totalOpenBalance,
    isPOTaxExempt: body.isPOTaxExempt,
    isManufacturer: body.isManufacturer,
    is1099Vendor: body.is1099Vendor,
    FirstSale: body.firstSale,
    POReference: body.poReference,
    referenceNo: body.referenceNo,
    rating: body.rating,
    taxID: body.taxID,
    URL: body.URL,
    NAICS: body.NAICS,
    DUNS: body.DUNS,
    documentCopies: body.documentCopies,
    SO_Description: body.soDescription,
    flatDiscount: body.flatDiscount,
    shelfLifeMinPct: body.shelfLifeMinPct,
    dunningGrace: body.dunningGrace,
    isAccountLogShip: body.isAccountLogShip,
    isAccountingWarehouseVolume: body.isAccountingWarehouseVolume,
    logshipmonthlyfee: body.logshipmonthlyfee,
    volumeqm3price: body.volumeqm3price,
    accoutingwarehouserentstarts: body.accoutingwarehouserentstarts,
    ...newObjValue,
    tableName: 'C_Bpartner'
  })
  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
})