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')
  const role = getCookie(event, 'logship_role')

  data['records'] = []
  const rangeDate = []

  if(query?.period == 'today') {
    const newDate = date.now('date')
    rangeDate.push({
      period: newDate,
      startDate: newDate+' 00:00:00',
      endDate: newDate+' 23:59:59'
    })
  } else if(query?.period == 'yesterday') {
    const newDate = date.sub(date.now('date'), 1, 'date')
    rangeDate.push({
      period: newDate,
      startDate: newDate+' 00:00:00',
      endDate: newDate+' 23:59:59'
    })
  } else if(query?.period == 'last_month') {
    for(let i = 0; i < 28; i++) {
      if(i == 0) {
        const newDate = date.now('date')
        rangeDate.push({
          period: `${newDate.split('-')?.[1] ?? '00'}/${newDate.split('-')?.[2] || (Number(i) + 1)}`,
          startDate: newDate+' 00:00:00',
          endDate: newDate+' 23:59:59'
        })
      } else {
        const newDate = date.sub(date.now('date'), i, 'date')
        rangeDate.push({
          period: `${newDate.split('-')?.[1] ?? '00'}/${newDate.split('-')?.[2] || (Number(i) + 1)}`,
          startDate: newDate+' 00:00:00',
          endDate: newDate+' 23:59:59'
        })
      }
    }
  } else if(query?.period == 'last_year') {
    for(let i = 0; i < 12; i++) {
      const subMonth = (Number(new Date().getMonth()) + 1) - i
      let newMonth = subMonth
      let newYear = new Date().getFullYear()
      if(subMonth <= 0) {
        newMonth = Number(subMonth) + 12
        newYear = Number(new Date().getFullYear()) - 1
      }

      const newDate = `${newYear}-${date.doubleFormat(newMonth)}`
      rangeDate.push({
        period: newDate,
        startDate: newDate+'-01 00:00:00',
        endDate: newDate+`-${date.daysInMonth(newYear, newMonth)} 23:59:59`
      })
    }
  } else {
    for(let i = 0; i < 7; i++) {
      if(i == 0) {
        const newDate = date.now('date')
        rangeDate.push({
          period: newDate,
          startDate: newDate+' 00:00:00',
          endDate: newDate+' 23:59:59'
        })
      } else {
        const newDate = date.sub(date.now('date'), i, 'date')
        rangeDate.push({
          period: newDate,
          startDate: newDate+' 00:00:00',
          endDate: newDate+' 23:59:59'
        })
      }
    }
  }

  for(const rgDate of rangeDate) {
    const newUserRole = JSON.parse(role ?? '{}')
    let filterByOrg = ''
    if(!newUserRole?.IsClientAdministrator) {
      filterByOrg = ` AND ad_org_id eq ${query?.organization_id ?? organizationId}`
    }

    const newDataSet = {}
    newDataSet['period'] = rgDate.period
    const newFilter = string.urlEncode(`IsSOTrx eq true AND created ge '${rgDate.startDate}' AND created le '${rgDate.endDate}'`+filterByOrg)
  
    const res1: any = await fetchHelper(event, `models/c_order?$filter=${newFilter}&$select=created`, 'GET', token, null)
    if(res1) {
      newDataSet['orders'] = res1?.['row-count'] ?? 0
    }
    
    const res2: any = await fetchHelper(event, `models/c_invoice?$filter=${newFilter}&$select=created`, 'GET', token, null)
    if(res2) {
      newDataSet['invoices'] = res2?.['row-count'] ?? 0
    }

    const res3: any = await fetchHelper(event, `models/r_request?$filter=${string.urlEncode(`created ge '${rgDate.startDate}' AND created le '${rgDate.endDate}'`+filterByOrg)}&$select=created`, 'GET', token, null)
    if(res3) {
      newDataSet['requests'] = res3?.['row-count'] ?? 0
    }

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

    data['records'].push(newDataSet)
  }
  

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