import refreshTokenHelper from "../../utils/refreshTokenHelper"
import getTokenHelper from "../../utils/getTokenHelper"
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)

  let newObjValue = {}
  if(body.movementTypeId) {
    newObjValue = {...newObjValue, 
      MovementType: {
        id: body.movementTypeId,
      }
    }
  }
  if(body.docTypeId) {
    newObjValue = {...newObjValue, 
      C_DocType_ID: {
        id: body.docTypeId,
        tableName: 'C_DocType'
      }
    }
  }
  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.userId) {
    newObjValue = {...newObjValue, 
      AD_User_ID: {
        id: body.userId,
        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.returnPartnerId) {
    newObjValue = {...newObjValue, 
      Return_BPartner_ID: {
        id: body.returnPartnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.returnPartnerLocationId) {
    newObjValue = {...newObjValue, 
      Return_Location_ID: {
        id: body.returnPartnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.returnUserId) {
    newObjValue = {...newObjValue, 
      Return_User_ID: {
        id: body.returnUserId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.warehouseId) {
    newObjValue = {...newObjValue, 
      M_Warehouse_ID: {
        id: body.warehouseId,
        tableName: 'M_Warehouse'
      }
    }
  }
  if(body.deliveryRuleId) {
    newObjValue = {...newObjValue, 
      DeliveryRule: {
        id: body.deliveryRuleId
      }
    }
  }
  if(body.freightCostRuleId) {
    newObjValue = {...newObjValue, 
      FreightCostRule: {
        id: body.freightCostRuleId
      }
    }
  }
  if(body.deliveryViaRuleId) {
    newObjValue = {...newObjValue, 
      DeliveryViaRule: {
        id: body.deliveryViaRuleId
      }
    }
  }
  if(body.priorityRuleId) {
    newObjValue = {...newObjValue, 
      PriorityRule: {
        id: body.priorityRuleId
      }
    }
  }
  if(body.orderId) {
    newObjValue = {...newObjValue, 
      C_Order_ID: {
        id: body.orderId,
        tableName: 'C_Order'
      }
    }
  }
  if(body.docStatusId) {
    newObjValue = {...newObjValue, 
      DocStatus: {
        id: body.docStatusId
      }
    }
  }
  if(body.salesRepId) {
    newObjValue = {...newObjValue, 
      SalesRep_ID: {
        id: body.salesRepId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.projectId) {
    newObjValue = {...newObjValue, 
      C_Project_ID: {
        id: body.projectId,
        tableName: 'C_Project'
      }
    }
  }
  if(body.campaignId) {
    newObjValue = {...newObjValue, 
      C_Campaign_ID: {
        id: body.campaignId,
        tableName: 'C_Campaign'
      }
    }
  }
  if(body.shipperId) {
    newObjValue = {...newObjValue, 
      M_Shipper_ID: {
        id: body.shipperId,
        tableName: 'M_Shipper'
      }
    }
  }
  if(body.organizationId) {
    newObjValue = {...newObjValue, 
      AD_Org_ID: {
        id: body.organizationId,
        tableName: 'AD_Org'
      }
    }
  }
  if(new Boolean(body.isCommissionedConfirmed)) {
    newObjValue = {...newObjValue, IsCommissionedConfirmed: body.isCommissionedConfirmed}
  }

  const res: any = await fetchHelper(event, 'models/m_inout/'+body.id, 'PUT', token, {
    isActive: body.isActive,
    documentNo: body.documentNo,
    description: body.description,
    movementDate: body.movementDate,
    processed: body.processed,
    isSOTrx: body.isSOTrx,
    isPrinted: body.isPrinted,
    dateAcct: body.dateAcct,
    POReference: body.poReference,
    freightAmt: body.freightAmt,
    chargeAmt: body.chargeAmt,
    dateOrdered: body.dateOrdered,
    sendEMail: body.sendEMail,
    noPackages: body.noPackages,
    isInTransit: body.isInTransit,
    isApproved: body.isApproved,
    isInDispute: body.isInDispute,
    volume: body.volume,
    weight: body.weight,
    isDropShip: body.isDropShip,
    processedOn: body.processedOn,
    isAlternateReturnAddress: body.isAlternateReturnAddress,
    ...newObjValue,
    tableName: 'M_Inout'
  })
  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)
      forceLogoutHelper(event, data)
    }
  }

  return data
})