import { string } from 'alga-js'
import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"
import fetchHelper from "../../../utils/fetchHelper"
import postgrestHelper from "../../../utils/postgrestHelper"

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)
  let id = getRouterParam(event, 'id')

  if(id === 'delivery_via_rule') {
    id = 152
  } else if(id === 'delivery_rule') {
    id = 151
  } else if(id === 'freight_cost_rule') {
    id = 153
  } else if(id === 'priority_rule') {
    id = 154
  } else if(id === 'payment_rule') {
    id = 195
  } else if(id === 'marketplace') {
    id = 1000003
  } else if(id === 'labelprinter') {
    id = 1000004
  }

  const res: any = await fetchHelper(event, `reference/${id}`, 'GET', token, null)
  if(res) {
    data = res
  }

  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
})