const db = require('./db')

function toNum(v) {
  if (v == null || v === '') return 0
  const n = Number(v)
  return Number.isFinite(n) ? Math.max(0, Math.floor(n)) : 0
}

function getStats() {
  const viewersRow = db.prepare(
    "SELECT COUNT(*) as n FROM visits WHERE last_seen > datetime('now', '-2 minutes')"
  ).get()
  const cumulativeRow = db.prepare('SELECT total FROM visitor_count WHERE id = 1').get()
  const feedbackRow = db.prepare('SELECT COUNT(*) as n FROM feedback').get()
  const shareRow = db.prepare('SELECT total FROM share_count WHERE id = 1').get()
  let realLikeCount = 0
  try {
    realLikeCount = toNum(db.prepare('SELECT total FROM like_count WHERE id = 1').get()?.total)
  } catch (_) {}
  let viewers = toNum(viewersRow?.n)
  let cumulative = toNum(cumulativeRow?.total)
  let feedbackCount = toNum(feedbackRow?.n)
  let shareCount = toNum(shareRow?.total)
  let likeCount = realLikeCount
  let display = null
  try {
    display = db.prepare('SELECT override_enabled, viewers, cumulative, share_count, like_count, feedback_count FROM display_stats WHERE id = 1').get()
  } catch (_) {}
  const useOverride = display && display.override_enabled === 1
  if (useOverride && display) {
    if (display.viewers != null) viewers = toNum(display.viewers)
    if (display.cumulative != null) cumulative = toNum(display.cumulative)
    if (display.share_count != null) shareCount = toNum(display.share_count)
    if (display.like_count != null) likeCount = toNum(display.like_count)
    else likeCount = realLikeCount
    if (display.feedback_count != null) feedbackCount = toNum(display.feedback_count)
  }
  return { viewers, cumulative, feedbackCount, shareCount, likeCount }
}

module.exports = { getStats }
