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.userLevelId) {
    newObjValue = {...newObjValue, 
      UserLevel: {
        id: body.userLevelId
      }
    }
  }
  if(body.currencyId) {
    newObjValue = {...newObjValue, 
      C_Currency_ID: {
        id: body.currencyId,
        tableName: 'C_Currency'
      }
    }
  }
  if(body.preferenceTypeId) {
    newObjValue = {...newObjValue, 
      PreferenceType: {
        id: body.preferenceTypeId
      }
    }
  }
  if(body.treeMenuId) {
    newObjValue = {...newObjValue, 
      AD_Tree_Menu_ID: {
        id: body.treeMenuId,
        tableName: 'AD_Tree'
      }
    }
  }
  if(body.roleTypeId) {
    newObjValue = {...newObjValue, 
      RoleType: {
        id: body.roleTypeId
      }
    }
  }
  if(body.treeOrgId) {
    newObjValue = {...newObjValue, 
      AD_Tree_Org_ID: {
        id: body.treeOrgId,
        tableName: 'AD_Tree'
      }
    }
  }

  const res: any = await event.context.fetch('models/ad_role/'+body.id, 'PUT', token, {
    isActive: body.isActive,
    name: body.name,
    description: body.description,
    amtApproval: body.amtApproval,
    isManual: body.isManual,
    isPersonalAccess: body.isPersonalAccess,
    isShowAcct: body.isShowAcct,
    isPersonalLock: body.isPersonalLock,
    isCanReport: body.isCanReport,
    isCanExport: body.isCanExport,
    isCanApproveOwnDoc: body.isCanApproveOwnDoc,
    isAccessAllOrgs: body.isAccessAllOrgs,
    isChangeLog: body.isChangeLog,
    overwritePriceLimit: body.overwritePriceLimit,
    isUseUserOrgAccess: body.isUseUserOrgAccess,
    confirmQueryRecords: body.confirmQueryRecords,
    maxQueryRecords: body.maxQueryRecords,
    Allow_Info_Account: body.allow_Info_Account,
    Allow_Info_Asset: body.allow_Info_Asset,
    Allow_Info_BPartner: body.allow_Info_BPartner,
    Allow_Info_InOut: body.allow_Info_InOut,
    Allow_Info_Invoice: body.allow_Info_Invoice,
    Allow_Info_Order: body.allow_Info_Order,
    Allow_Info_Payment: body.allow_Info_Payment,
    Allow_Info_Product: body.allow_Info_Product,
    Allow_Info_Resource: body.allow_Info_Resource,
    Allow_Info_Schedule: body.allow_Info_Schedule,
    isDiscountUptoLimitPrice: body.isDiscountUptoLimitPrice,
    isDiscountAllowedOnTotal: body.isDiscountAllowedOnTotal,
    isMenuAutoExpand: body.isMenuAutoExpand,
    isMasterRole: body.isMasterRole,
    isAccessAdvanced: body.isAccessAdvanced,
    isClientAdministrator: body.isClientAdministrator,
    ...newObjValue,
    tableName: 'AD_Role'
  })
  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
})