import { EntityManager } from 'typeorm'

import { User } from '@things-factory/auth-base'
import { Domain, ListParam } from '@things-factory/shell'
import { getPermittedBizplaceIds } from '@things-factory/biz-base'

// Simple in-memory cache with 30 second TTL
const dashboardCache = new Map<string, { data: any; expires: number }>()

// Auto-cleanup expired cache entries every 5 minutes
setInterval(() => {
  const now = Date.now()
  for (const [key, value] of dashboardCache.entries()) {
    if (value.expires <= now) {
      dashboardCache.delete(key)
    }
  }
}, 5 * 60 * 1000)

export const outboundOrderByStatusResolver = {
  async outboundOrderByStatus(_: any, params: ListParam, context: any) {
    const { domain, user, tx }: { domain: Domain; user: User; tx: EntityManager } = context.state
    const bizplaceId: string = params.filters.find((filter: any) => filter.name === 'bizplace')?.value || 'ALL'
    const v4 = new RegExp(/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i)
    let bizplaceIds: string[] = []

    if (bizplaceId && (bizplaceId == 'ALL' || bizplaceId.match(v4))) {
      bizplaceIds = bizplaceId && bizplaceId != 'ALL' ? [bizplaceId] : await getPermittedBizplaceIds(domain, user)
    } else throw new Error('invalid bizplaceId')

    // Create cache key from domain and sorted bizplace IDs
    const cacheKey = `${domain.id}:${bizplaceIds.sort().join(',')}`
    const now = Date.now()

    // Check cache first
    const cached = dashboardCache.get(cacheKey)
    if (cached && cached.expires > now) {
      return cached.data
    }

    // Cache miss - query database
    let items = await tx.query(`Select * from dashboard($1,$2) `, [bizplaceIds, domain.id])

    const orderStatus: { status: string; count: number }[] = items

    // Store in cache for 30 seconds
    dashboardCache.set(cacheKey, {
      data: orderStatus,
      expires: now + 30000
    })

    return orderStatus
  }
}
