import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"
import { listingTablesAvailable, listingBackendInfo, listChanges, eventFetch } from "../../../utils/listings/listingStore"
import { getLastFlushRun } from "../../../utils/listings/outbox"

// GET /api/sales/sms/status?orderSourceId=
// Health of the listing pipeline: tables reachable, timer config, last flush run,
// queued / sending / sent / error counts (optionally for one order source).
const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const q = getQuery(event)
  const orderSourceId = Number(q.orderSourceId) || undefined
  const f = eventFetch(event, token)
  const available = await listingTablesAvailable(f)
  const counts: Record<string, number> = { queued: 0, sending: 0, sent: 0, error: 0 }
  if (available) {
    const rows = await listChanges(f, { status: ['queued', 'sending', 'sent', 'error'], ...(orderSourceId ? { orderSourceId } : {}) }, 2000)
    for (const r of rows) counts[r.changeStatus] = (counts[r.changeStatus] || 0) + 1
  }
  const config: any = useRuntimeConfig()
  return {
    status: 200,
    tables: { ...listingBackendInfo(), available },
    flush: {
      timerEnabled: !(process.env.LISTING_FLUSH_ENABLED === '0' || process.env.LISTING_FLUSH_ENABLED === 'false') && !!config.api?.idempieretoken,
      intervalMs: Math.max(15_000, Number(process.env.LISTING_FLUSH_INTERVAL_MS) || 60_000),
      debounceMs: Math.max(0, Number(process.env.LISTING_FLUSH_DEBOUNCE_MS ?? 20_000)),
      patchThreshold: Math.max(0, Number(process.env.LISTING_PATCH_THRESHOLD ?? 50)),
      lastRun: getLastFlushRun()
    },
    counts
  }
}

export default defineEventHandler(async (event) => {
  let data: any = {}
  try {
    data = await handleFunc(event)
  } catch (err: any) {
    try {
      const 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
})
