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.organizationId) {
    newObjValue = {...newObjValue, 
      AD_Org_ID: {
        id: body.organizationId,
        tableName: 'AD_Org'
      }
    }
  }
  if(body.treeMenuId) {
    newObjValue = {...newObjValue, 
      AD_Tree_Menu_ID: {
        id: body.treeMenuId,
        tableName: 'AD_Tree'
      }
    }
  }
  if(body.treeOrgId) {
    newObjValue = {...newObjValue, 
      AD_Tree_Org_ID: {
        id: body.treeOrgId,
        tableName: 'AD_Tree'
      }
    }
  }
  if(body.treeBPartnerId) {
    newObjValue = {...newObjValue, 
      AD_Tree_BPartner_ID: {
        id: body.treeBPartnerId,
        tableName: 'AD_Tree'
      }
    }
  }
  if(body.treeProjectId) {
    newObjValue = {...newObjValue, 
      AD_Tree_Project_ID: {
        id: body.treeProjectId,
        tableName: 'AD_Tree'
      }
    }
  }
  if(body.treeSalesRegionId) {
    newObjValue = {...newObjValue, 
      AD_Tree_SalesRegion_ID: {
        id: body.treeSalesRegionId,
        tableName: 'AD_Tree'
      }
    }
  }
  if(body.treeProductId) {
    newObjValue = {...newObjValue, 
      AD_Tree_Product_ID: {
        id: body.treeProductId,
        tableName: 'AD_Tree'
      }
    }
  }

  if(body.id) {
    const res: any = await event.context.fetch('models/ad_clientinfo/'+body.id, 'PUT', token, {
      isDiscountLineAmt: body.isDiscountLineAmt,
      keepLogDays: body.keepLogDays,
      isConfirmOnDocClose: body.isConfirmOnDocClose,
      isConfirmOnDocVoid: body.isConfirmOnDocVoid,
      ...newObjValue,
      tableName: 'AD_Clientinfo'
    })
    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
})