import refreshTokenHelper from "../../utils/refreshTokenHelper"
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.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.docBaseTypeId) {
    newObjValue = {...newObjValue, 
      DocBaseType: {
        id: body.docBaseTypeId
      }
    }
  }*/
  if(body.salesRepId) {
    newObjValue = {...newObjValue, 
      SalesRep_ID: {
        id: body.salesRepId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.userId) {
    newObjValue = {...newObjValue, 
      AD_User_ID: {
        id: body.userId,
        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.paymentRuleId) {
    newObjValue = {...newObjValue, 
      PaymentRule: {
        id: body.paymentRuleId
      }
    }
  }
  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.orderId) {
    newObjValue = {...newObjValue, 
      C_Order_ID: {
        id: body.orderId,
        tableName: 'C_Order'
      }
    }
  }
  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.invoiceLines) {
    newObjValue = {...newObjValue, 
      C_InvoiceLine: body.invoiceLines
    }
  }
  if(body.paymentSchedules) {
    newObjValue = {...newObjValue, 
      C_InvoicePaySchedule: body.paymentSchedules
    }
  }

  const res: any = await fetchHelper(event, 'models/c_invoice', 'POST', token, {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    documentNo: body.documentNo,
    description: body.description,
    isApproved: body.isApproved,
    isPaid: body.isPaid,
    isPrinted: body.isPrinted,
    isTransferred: body.isTransferred,
    dateOrdered: body.dateOrdered,
    dateAcct: body.dateAcct,
    totalLines: body.totalLines,
    grandTotal: body.grandTotal,
    chargeAmt: body.chargeAmt,
    processed: body.processed,
    isSOTrx: body.isSOTrx,
    isDiscountPrinted: body.isDiscountPrinted,
    isTaxIncluded: body.isTaxIncluded,
    sendEMail: body.sendEMail,
    isSelfService: body.isSelfService,
    processedOn: body.processedOn,
    isPayScheduleValid: body.isPayScheduleValid,
    POReference: body?.poReference || '',
    dateInvoiced: body.dateInvoiced,
    isInDispute: body.isInDispute,
    isFixedAssetInvoice: body.isFixedAssetInvoice,
    isOverrideCurrencyRate: body.isOverrideCurrencyRate,
    ...newObjValue,
    tableName: 'C_Invoice'
  })
  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
})