import { string, date } 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 query = getQuery(event)
  const organizationId = getCookie(event, 'logship_organization_id')

  //@ts-ignore
  //const res: any[] = await postgrestHelper(event, `xx_bi_order_quantity_today`, 'GET', null)

  const newFilter = string.urlEncode(`IsSOTrx eq true AND created ge '${query?.created_at ?? date.now('date')}' AND ad_org_id eq ${query?.organization_id ?? organizationId}`)
  
  const res1: any = await fetchHelper(event, `models/c_order?$filter=${newFilter}&$select=created`, 'GET', token, null)
  if(res1) {
    data['orders'] = res1?.['row-count'] ?? 0
  }
  
  const res2: any = await fetchHelper(event, `models/c_invoice?$filter=${newFilter}&$select=created`, 'GET', token, null)
  if(res2) {
    data['invoices'] = res2?.['row-count'] ?? 0
  }

  const res3: any = await fetchHelper(event, `models/r_request?$filter=${string.urlEncode(`created ge '${query?.created_at ?? date.now('date')}' AND ad_org_id eq ${query?.organization_id ?? organizationId}`)}&$select=created`, 'GET', token, null)
  if(res3) {
    data['requests'] = res3?.['row-count'] ?? 0
  }

  const res4: any = await fetchHelper(event, `models/m_inout?$filter=${newFilter}&$select=created`, 'GET', token, null)
  if(res4) {
    data['shipments'] = res4?.['row-count'] ?? 0
  }

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

    return data
})