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)
  const id = getRouterParam(event, 'id')

  //@ts-ignore
  const res: any[] = await postgrestHelper(event, `xy_mat_ad_preference?ad_window_id=eq.${id}`, 'GET', null)
  if(res) {
    for(let record of Array.from(res)) {
      data[record.attribute] = {
        id: record.value,
        identifier: record.identifier,
        attribute: record.attribute
      }
    }
  }

  /*const res: any = await fetchHelper(event, `models/ad_preference?$filter=${string.urlEncode('AD_Window_ID eq '+id+' AND IsActive eq true')}&$select=Attribute,Value`, 'GET', token, null)
  if(res?.records) {
    for(let record of res.records) {
      data[record.Attribute] = {
        id: record.Value,
        identifier: 'No Identifier',
        attribute: record.Attribute
      }
      if(record.Attribute === 'C_BPartner_ID') {
        const res2: any = await fetchHelper(event, `models/c_bpartner/${record.Value}`, 'GET', token, null)
        if(res2) {
          data['C_BPartner_ID']['identifier'] = res2.Name || 'No Identifier'
        }
      }
    }
  }*/

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