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.uomToId) {
    newObjValue = {...newObjValue, 
      C_UOM_To_ID: {
        id: body.uomToId,
        tableName: 'C_UOM'
      }
    }
  }
  if(body.productId) {
    newObjValue = {...newObjValue, 
      M_Product_ID: {
        id: body.productId,
        tableName: 'M_Product'
      }
    }
  }

  if(body.uomId) {
    const res: any = await fetchHelper(event, 'models/c_uom_conversion', 'POST', token, {
      AD_Org_ID: {
        id: body.organizationId,
        tableName: 'AD_Org'
      },
      isActive: body.isActive,
      multiplyRate: body.multiplyRate,
      divideRate: body.divideRate,
      C_UOM_ID: {
        id: body.uomId,
        tableName: 'C_UOM'
      },
      ...newObjValue,
      tableName: 'c_uom_conversion'
    })
    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.details || 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.details || error.message || error.statusMessage
        }
        forceLogoutHelper(event, data)
      }
    }
  }

  return data
})