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 token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

  let newObjValue = {}
  if(body.printFormatId) {
    newObjValue = {...newObjValue, 
      Dunning_PrintFormat_ID: {
        id: body.printFormatId,
        tableName: 'ad_printformat'
      }
    }
  }
  if(body.paymentTermId) {
    newObjValue = {...newObjValue, 
      C_PaymentTerm_ID: {
        id: body.paymentTermId,
        tableName: 'C_PaymentTerm'
      }
    }
  }
  if(body.invoiceCollectionTypeId) {
    newObjValue = {...newObjValue, 
      InvoiceCollectionType: {
        id: body.invoiceCollectionTypeId
      }
    }
  }

  if(body.id) {
    const res: any = await fetchHelper(event, 'models/c_dunninglevel/'+body.id, 'PUT', token, {
      isActive: body.isActive,
      name: body.name,
      description: body.description,
      printName: body.printName,
      daysAfterDue: body.daysAfterDue,
      daysBetweenDunning: body.daysBetweenDunning,
      note: body.note,
      interestPercent: body.interestPercent,
      feeAmt: body.feeAmt,
      isShowAllDue: body.isShowAllDue,
      isShowNotDue: body.isShowNotDue,
      isSetCreditStop: body.isSetCreditStop,
      isSetPaymentTerm: body.isSetPaymentTerm,
      isStatement: body.isStatement,
      chargeInterest: body.chargeInterest,
      chargeFee: body.chargeFee,
      ...newObjValue,
      tableName: 'c_dunninglevel'
    })
    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) {
    if(err.status >= 500 || err.statusCode >= 500) {
      data = {
        status: err.status || err.statusCode,
        message: err.detail || err.message || err.statusMessage
      }
    } else {
    try {
        let authToken: any = await refreshTokenHelper(event)
        data = await handleFunc(event, authToken)
      } catch(error: any) {
        data = {
          status: error.status || error.statusCode || 500,
          message: error.detail || error.message || error.statusMessage
        }
        forceLogoutHelper(event, data)
      }
    }
  }

  return data
})