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.docStatusId) {
    newObjValue = {...newObjValue, 
      DocStatus: {
        id: body.docStatusId,
      }
    }
  }
  if(body.docTypeId) {
    newObjValue = {...newObjValue, 
      C_DocType_ID: {
        id: body.docTypeId,
        tableName: 'C_DocType'
      }
    }
  }
  if(body.docTypeTargetId) {
    newObjValue = {...newObjValue, 
      C_DocTypeTarget_ID: {
        id: body.docTypeTargetId,
        tableName: 'C_DocTypeTarget'
      }
    }
  }
  if(body.salesRepId) {
    newObjValue = {...newObjValue, 
      SalesRep_ID: {
        id: body.salesRepId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.paymentTermId) {
    newObjValue = {...newObjValue, 
      C_PaymentTerm_ID: {
        id: body.paymentTermId,
        tableName: 'C_PaymentTerm'
      }
    }
  }
  if(body.currencyId) {
    newObjValue = {...newObjValue, 
      C_Currency_ID: {
        id: body.currencyId,
        tableName: 'C_Currency'
      }
    }
  }
  if(body.invoiceRuleId) {
    newObjValue = {...newObjValue, 
      InvoiceRule: {
        id: body.invoiceRuleId
      }
    }
  }
  if(body.deliveryViaRuleId) {
    newObjValue = {...newObjValue, 
      DeliveryViaRule: {
        id: body.deliveryViaRuleId
      }
    }
  }
  if(body.deliveryRuleId) {
    newObjValue = {...newObjValue, 
      DeliveryRule: {
        id: body.deliveryRuleId
      }
    }
  }
  if(body.priorityRuleId) {
    newObjValue = {...newObjValue, 
      PriorityRule: {
        id: body.priorityRuleId
      }
    }
  }
  if(body.freightCostRuleId) {
    newObjValue = {...newObjValue, 
      FreightCostRule: {
        id: body.freightCostRuleId
      }
    }
  }
  if(body.paymentRuleId) {
    newObjValue = {...newObjValue, 
      PaymentRule: {
        id: body.paymentRuleId
      }
    }
  }
  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.partnerId) {
    newObjValue = {...newObjValue, 
      C_BPartner_ID: {
        id: body.partnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.partnerLocationId) {
    newObjValue = {...newObjValue, 
      C_BPartner_Location_ID: {
        id: body.partnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.cashLineId) {
    newObjValue = {...newObjValue, 
      C_CashLine_ID: {
        id: body.cashLineId,
        tableName: 'C_CashLine'
      }
    }
  }
  if(body.billPartnerId) {
    newObjValue = {...newObjValue, 
      Bill_BPartner_ID: {
        id: body.billPartnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.billPartnerLocationId) {
    newObjValue = {...newObjValue, 
      Bill_Location_ID: {
        id: body.billPartnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.organizationId) {
    newObjValue = {...newObjValue, 
      AD_Org_ID: {
        id: body.organizationId,
        tableName: 'AD_Org'
      }
    }
  }
  if(body.shipperId) {
    newObjValue = {...newObjValue, 
      M_Shipper_ID: {
        id: body.shipperId,
        tableName: 'M_Shipper'
      }
    }
  }
  if(body.freightCategoryId) {
    newObjValue = {...newObjValue, 
      M_FreightCategory_ID: {
        id: body.freightCategoryId,
        tableName: 'M_FreightCategory'
      }
    }
  }
  if(body.userId) {
    newObjValue = {...newObjValue, 
      AD_User_ID: {
        id: body.userId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.billUserId) {
    newObjValue = {...newObjValue, 
      Bill_User_ID: {
        id: body.billUserId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.dropShipPartnerId) {
    newObjValue = {...newObjValue, 
      DropShip_BPartner_ID: {
        id: body.dropShipPartnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.dropShipPartnerLocationId) {
    newObjValue = {...newObjValue, 
      DropShip_Location_ID: {
        id: body.dropShipPartnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.dropShipUserId) {
    newObjValue = {...newObjValue, 
      DropShip_User_ID: {
        id: body.dropShipUserId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.conversionTypeId) {
    newObjValue = {...newObjValue, 
      C_ConversionType_ID: {
        id: body.conversionTypeId,
        tableName: 'C_ConversionType'
      }
    }
  }
  if(body.orderSourceId) {
    newObjValue = {...newObjValue, 
      C_OrderSource_ID: {
        id: body.orderSourceId,
        tableName: 'C_OrderSource'
      }
    }
  }
  if(body.promotionCode) {
    newObjValue = {...newObjValue, 
      PromotionCode: body.promotionCode
    }
  }
  if(body.shopware6OrderId) {
    newObjValue = {...newObjValue, 
      shopware6_order_id: body.shopware6OrderId
    }
  }
  if(body.shopifyOrderId) {
    newObjValue = {...newObjValue, 
      shopify_order_id: body.shopifyOrderId
    }
  }
  if(body.xentralOrderId) {
    newObjValue = {...newObjValue, 
      xentral_order_id: body.xentralOrderId
    }
  }
  if(body.amazonOrderId) {
    newObjValue = {...newObjValue, 
      amazon_order_id: body.amazonOrderId
    }
  }
  if(body.plentyOneOrderId) {
    newObjValue = {...newObjValue, 
      plentyone_order_id: body.plentyOneOrderId
    }
  }
  if(body.externalOrderId) {
    newObjValue = {...newObjValue,
      ExternalOrderId: body.externalOrderId
    }
  }
  if(body.ebayOrderId) {
    newObjValue = {...newObjValue,
      ebay_order_id: body.ebayOrderId
    }
  }
  if(body.temuOrderId) {
    newObjValue = {...newObjValue,
      temu_order_id: body.temuOrderId
    }
  }
  if(body.jtlMerchantOrderNumber) {
    newObjValue = {...newObjValue,
      jtl_merchant_order_number: body.jtlMerchantOrderNumber
    }
  }
  if(body.attachmentTrackingnumber) {
    newObjValue = {...newObjValue,
      attachment_trackingnumber: body.attachmentTrackingnumber
    }
  }
  if(body.isRelabelByFulfillmentProvider !== undefined && body.docStatusId != 'CO') {
    newObjValue = {...newObjValue,
      isRelabelByFulfillmentProvider: body.isRelabelByFulfillmentProvider === true
    }
  }
  if(body.docStatusId != 'CO') {
    newObjValue = {
      ...newObjValue,
      isActive: body.isActive,
      freightAmt: body.freightAmt,
      chargeAmt: body.chargeAmt,
      isSOTrx: body.isSOTrx,
      isDiscountPrinted: body.isDiscountPrinted,
      isTaxIncluded: body.isTaxIncluded,
      isSelected: body.isSelected,
      sendEMail: body.sendEMail,
      isSelfService: body.isSelfService,
      isDropShip: body.isDropShip,
      processedOn: body.processedOn,
      isPayScheduleValid: body.isPayScheduleValid,
      isPriviledgedRate: body.isPriviledgedRate,
    }
  }
  /*if(body.orderLines) {
    newObjValue = {...newObjValue, 
      C_OrderLine: body.orderLines.map((i: any) => {
        if(i.id == '') {
          delete i.id
        }
        return i
      })
    }
  }
  if(body.paymentSchedules) {
    newObjValue = {...newObjValue, 
      C_OrderPaySchedule: body.paymentSchedules.map((i: any) => {
        if(i.id == '') {
          delete i.id
        }
        return i
      })
    }
  }*/

  const res: any = await event.context.fetch('models/c_order/'+body.id, 'PUT', token, {
    documentNo: body.documentNo,
    POReference: body.POReference,
    description: body.description,
    PeriodPerformanceDate: body.periodPerformanceDate || null,
    isApproved: body.isApproved,
    dateOrdered: body.dateOrdered,
    datePromised: body.datePromised,
    dateAcct: body.dateAcct,
    totalLines: body.totalLines,
    grandTotal: body.grandTotal,
    ...newObjValue,
    tableName: 'C_Order'
  })
  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
})