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.priorityId) {
    newObjValue = {...newObjValue, 
      Priority: {
        id: body.priorityId
      }
    }
  }
  if(body.dueTypeId) {
    newObjValue = {...newObjValue, 
      DueType: {
        id: body.dueTypeId
      }
    }
  }
  if(body.salesRepId) {
    newObjValue = {...newObjValue, 
      SalesRep_ID: {
        id: body.salesRepId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.partnerId) {
    newObjValue = {...newObjValue, 
      C_BPartner_ID: {
        id: body.partnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.userId) {
    newObjValue = {...newObjValue, 
      AD_User_ID: {
        id: body.userId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.nextActionId) {
    newObjValue = {...newObjValue, 
      NextAction: {
        id: body.nextActionId
      }
    }
  }
  if(body.requestTypeId) {
    newObjValue = {...newObjValue, 
      R_RequestType_ID: {
        id: body.requestTypeId,
        tableName: 'R_RequestType'
      }
    }
  }
  if(body.groupId) {
    newObjValue = {...newObjValue, 
      R_Group_ID: {
        id: body.groupId,
        tableName: 'R_Group'
      }
    }
  }
  if(body.categoryId) {
    newObjValue = {...newObjValue, 
      R_Category_ID: {
        id: body.categoryId,
        tableName: 'R_Category'
      }
    }
  }
  if(body.statusId) {
    newObjValue = {...newObjValue, 
      R_Status_ID: {
        id: body.statusId,
        tableName: 'R_Status'
      }
    }
  }
  if(body.resolutionId) {
    newObjValue = {...newObjValue, 
      R_Resolution_ID: {
        id: body.resolutionId,
        tableName: 'R_Resolution'
      }
    }
  }
  if(body.priorityUserId) {
    newObjValue = {...newObjValue, 
      PriorityUser: {
        id: body.priorityUserId
      }
    }
  }
  if(body.confidentialTypeId) {
    newObjValue = {...newObjValue, 
      ConfidentialType: {
        id: body.confidentialTypeId
      }
    }
  }
  if(body.confidentialTypeEntryId) {
    newObjValue = {...newObjValue, 
      ConfidentialTypeEntry: {
        id: body.confidentialTypeEntryId
      }
    }
  }
  if(body.roleId) {
    newObjValue = {...newObjValue, 
      AD_Role_ID: {
        id: body.roleId,
        tableName: 'AD_Role'
      }
    }
  }
  if(body.standardResponseId) {
    newObjValue = {...newObjValue, 
      R_StandardResponse_ID: {
        id: body.standardResponseId,
        tableName: 'R_StandardResponse'
      }
    }
  }
  if(body.mailTextId) {
    newObjValue = {...newObjValue, 
      R_MailText_ID: {
        id: body.mailTextId,
        tableName: 'R_MailText'
      }
    }
  }
  if(body.taskStatusId) {
    newObjValue = {...newObjValue, 
      TaskStatus: {
        id: body.taskStatusId
      }
    }
  }
  if(body.activityId) {
    newObjValue = {...newObjValue, 
      C_Activity_ID: {
        id: Number(body.activityId),
        tableName: 'C_Activity'
      }
    }
  }
  if(body.assetId) {
    newObjValue = {...newObjValue, 
      A_Asset_ID: {
        id: body.assetId,
        tableName: 'A_Asset'
      }
    }
  }
  if(body.projectId) {
    newObjValue = {...newObjValue, 
      C_Project_ID: {
        id: body.projectId,
        tableName: 'C_Project'
      }
    }
  }
  if(body.orderId) {
    newObjValue = {...newObjValue, 
      C_Order_ID: {
        id: body.orderId,
        tableName: 'C_Order'
      }
    }
  }
  if(body.invoiceId) {
    newObjValue = {...newObjValue, 
      C_Invoice_ID: {
        id: body.invoiceId,
        tableName: 'C_Invoice'
      }
    }
  }
  if(body.paymentId) {
    newObjValue = {...newObjValue, 
      C_Payment_ID: {
        id: body.paymentId,
        tableName: 'C_Payment'
      }
    }
  }
  if(body.inOutId) {
    newObjValue = {...newObjValue, 
      M_InOut_ID: {
        id: body.inOutId,
        tableName: 'M_InOut'
      }
    }
  }
  if(body.productId) {
    newObjValue = {...newObjValue, 
      M_Product_ID: {
        id: body.productId,
        tableName: 'M_Product'
      }
    }
  }
  if(body.productSpentId) {
    newObjValue = {...newObjValue, 
      M_ProductSpent_ID: {
        id: body.productSpentId,
        tableName: 'M_Product'
      }
    }
  }
  if(body.rmaId) {
    newObjValue = {...newObjValue, 
      M_RMA_ID: {
        id: body.rmaId,
        tableName: 'M_RMA'
      }
    }
  }
  if(body.campaignId) {
    newObjValue = {...newObjValue, 
      C_Campaign_ID: {
        id: body.campaignId,
        tableName: 'C_Campaign'
      }
    }
  }

  if(body.dateNextAction) {
    newObjValue = {...newObjValue,  dateNextAction: body.dateNextAction}
  }
  if(body.result) {
    newObjValue = {...newObjValue,  result: body.result}
  }
  if(body.lastResult) {
    newObjValue = {...newObjValue,  lastResult: body.lastResult}
  }
  if(body.qtyPlan) {
    newObjValue = {...newObjValue,  qtyPlan: body.qtyPlan}
  }
  if(body.startTime) {
    newObjValue = {...newObjValue,  startTime: body.startTime}
  }
  if(body.startDate) {
    newObjValue = {...newObjValue,  startDate: body.startDate}
  }
  if(body.endTime) {
    newObjValue = {...newObjValue,  endTime: body.endTime}
  }
  if(body.endDate) {
    newObjValue = {...newObjValue,  closeDate: body.endDate}
  }
  if(body.documentNo) {
    newObjValue = {...newObjValue,  documentNo: body.documentNo}
  }

  const res: any = await event.context.fetch('models/r_request/'+body.id, 'PUT', token, {
    isActive: body.isActive,
    requestAmt: body.requestAmt,
    summary: body.summary,
    isEscalated: body.isEscalated,
    //dateLastAction: body.dateLastAction,
    processed: body.processed,
    //isSelfService: body.isSelfService,
    isInvoiced: body.isInvoiced,
    qtySpent: body.qtySpent,
    qtyInvoiced: body.qtyInvoiced,
    ...newObjValue,
    tableName: 'R_Request'
  })
  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
})