const { query } = require('../../utils/db')

// INSERT IGNORE on the UNIQUE dedupe_key — a re-ingested event (WS-reconnect
// backfill overlap) is silently skipped rather than duplicated. Returns true if
// a new row was actually inserted.
async function insertIgnore({ kind, t, bootId, payload, dedupeKey }) {
  const res = await query(
    `INSERT IGNORE INTO shard_events (kind, t, boot_id, payload, dedupe_key)
     VALUES (?, ?, ?, ?, ?)`,
    [kind, t, bootId || null, JSON.stringify(payload), dedupeKey],
  )
  return res.affectedRows > 0
}

// Recent events, newest first. Filter by a single `kind`, or an allowlist of
// `kinds` (IN clause) — the public feed uses the allowlist so it can never leak
// staff/sensitive kinds. limit is clamped by the model.
async function list({ kind, kinds, limit }) {
  if (kinds && kinds.length) {
    const placeholders = kinds.map(() => '?').join(', ')
    return query(
      `SELECT id, kind, t, boot_id, payload, created_at
         FROM shard_events WHERE kind IN (${placeholders}) ORDER BY t DESC LIMIT ?`,
      [...kinds, limit],
    )
  }
  if (kind) {
    return query(
      `SELECT id, kind, t, boot_id, payload, created_at
         FROM shard_events WHERE kind = ? ORDER BY t DESC LIMIT ?`,
      [kind, limit],
    )
  }
  return query(
    `SELECT id, kind, t, boot_id, payload, created_at
       FROM shard_events ORDER BY t DESC LIMIT ?`,
    [limit],
  )
}

module.exports = { insertIgnore, list }
