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"

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

  let filter = string.urlEncode(`DocBaseType eq '${id}'`)
  if(id === 'SOO') {
    filter = string.urlEncode(`DocBaseType eq '${id}' AND DocSubTypeSO neq 'RM'`)
  } else if(id === 'POO') {
    filter = string.urlEncode(`DocBaseType eq '${id}' AND Name neq 'Vendor Return Material'`)
  } else if(id === 'SIN' || id === 'PIN') {
    filter = string.urlEncode(`DocBaseType eq 'ARI' OR DocBaseType eq 'ARC'`)
  } else if(id === 'SPR' || id === 'PPR') {
    filter = string.urlEncode(`DocBaseType eq 'APP' OR DocBaseType eq 'ARR'`)
  } else if(id === 'MMIPI') {
    filter = string.urlEncode(`DocBaseType eq 'MMI' AND DocSubTypeInv eq 'PI'`)
  } else if(id === 'MMS') {
    filter = string.urlEncode(`DocBaseType eq '${id}' AND Name neq 'MM Vendor Return'`)
  } else if(id === 'MMR') {
    filter = string.urlEncode(`DocBaseType eq '${id}' AND Name neq 'MM Customer Return'`)
  } else if(id === 'MVR') {
    filter = string.urlEncode(`DocBaseType eq 'MMS' AND Name eq 'MM Vendor Return'`)
  } else if(id === 'MCR') {
    filter = string.urlEncode(`DocBaseType eq 'MMR' AND Name eq 'MM Customer Return'`)
  } else if(id === 'CRM') {
    filter = string.urlEncode(`DocBaseType eq 'SOO' AND DocSubTypeSO eq 'RM' AND IsSOTrx eq true`)
  } else if(id === 'VRM') {
    filter = string.urlEncode(`DocBaseType eq 'POO' AND DocSubTypeSO eq 'RM' AND IsSOTrx eq false`)
  }

  

  //@ts-ignore
  const res: any = await fetchHelper(event, `models/c_doctype?$filter=${filter}`, '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
})