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.replicationStrategyId) {
    newObjValue = {...newObjValue, 
      AD_ReplicationStrategy_ID: {
        id: body.replicationStrategyId,
        tableName: 'AD_ReplicationStrategy'
      }
    }
  }
  if(body.tenantId) {
    newObjValue = {...newObjValue, 
      AD_Client_ID: {
        id: body.tenantId,
        tableName: 'AD_Client'
      }
    }
  }

  const res: any = await fetchHelper(event, 'models/ad_org', 'POST', token, {
    isActive: body.isActive ?? true,
    name: body.name,
    description: body.description || '',
    value: body.value || '',
    isSummary: body.isSummary ?? false,
    ...newObjValue,
    AD_Org_ID: {
      id: 0,
      tableName: 'AD_Org'
    },
    tableName: 'AD_Org'
  })
  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
})