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.creditCardTypeId) {
    newObjValue = {...newObjValue, 
      CreditCardType: {
        id: body.creditCardTypeId,
      }
    }
  }
  if(body.bankAccountId) {
    newObjValue = {...newObjValue, 
      C_BankAccount_ID: {
        id: body.bankAccountId,
        tableName: 'C_BankAccount'
      }
    }
  }
  if(body.trxTypeId) {
    newObjValue = {...newObjValue, 
      TrxType: {
        id: body.trxTypeId
      }
    }
  }
  if(body.tenderTypeId) {
    newObjValue = {...newObjValue, 
      TenderType: {
        id: body.tenderTypeId
      }
    }
  }
  if(body.currencyId) {
    newObjValue = {...newObjValue, 
      C_Currency_ID: {
        id: body.currencyId,
        tableName: 'C_Currency'
      }
    }
  }
  if(body.docTypeId) {
    newObjValue = {...newObjValue, 
      C_DocType_ID: {
        id: body.docTypeId,
        tableName: 'C_DocType'
      }
    }
  }
  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.docStatusId) {
    newObjValue = {...newObjValue, 
      DocStatus: {
        id: body.docStatusId
      }
    }
  }
  if(body.partnerId) {
    newObjValue = {...newObjValue, 
      C_BPartner_ID: {
        id: body.partnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.chargeId) {
    newObjValue = {...newObjValue, 
      C_Charge_ID: {
        id: body.chargeId,
        tableName: 'C_Charge'
      }
    }
  }
  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'
      }
    }
  }

  const res: any = await event.context.fetch('models/c_payment', 'POST', token, {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    documentNo: body.documentNo,
    description: body.description,
    isApproved: body.isApproved,
    processed: body.processed,
    creditCardNumber: body.creditCardNumber,
    creditCardExpMM: body.creditCardExpMM,
    creditCardExpYY: body.creditCardExpYY,
    creditCardVV: body.creditCardVV,
    isReconciled: body.isReconciled,
    taxAmt: body.taxAmt,
    discountAmt: body.discountAmt,
    payAmt: body.payAmt,
    dateTrx: body.dateTrx,
    isAllocated: body.isAllocated,
    isOnline: body.isOnline,
    isReceipt: body.isReceipt,
    writeOffAmt: body.writeOffAmt,
    overUnderAmt: body.overUnderAmt,
    isOverUnderPayment: body.isOverUnderPayment,
    isSelfService: body.isSelfService,
    isDelayedCapture: body.isDelayedCapture,
    chargeAmt: body.chargeAmt,
    R_CVV2Match: body.R_CVV2Match,
    dateAcct: body.dateAcct,
    isPrepayment: body.isPrepayment,
    processedOn: body.processedOn,
    isVoided: body.isVoided,
    isOverrideCurrencyRate: body.isOverrideCurrencyRate,
    routingNo: body.routingNo,
    accountNo: body.accountNo,
    A_Zip: body.A_Zip,
    A_Ident_DL: body.A_Ident_DL,
    A_Ident_SSN: body.A_Ident_SSN,
    A_EMail: body.A_EMail,
    voiceAuthCode: body.voiceAuthCode,
    Orig_TrxID: body.orig_TrxID,
    micr: body.micr,
    checkNo: body.checkNo,
    A_Name: body.A_Name,
    A_Street: body.A_Street,
    A_City: body.A_City,
    A_State: body.A_State,
    A_Country: body.A_Country,
    swiftCode: body.swiftCode,
    ...newObjValue,
    tableName: 'C_Payment'
  })
  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
})