-- ═══════════════════════════════════════════════════════════════
-- 032: coin_log — audit + dedup table for coin-only events
--
-- Until now coins were always a side-effect of XP (1 coin per 10 XP
-- in awardXP), and we had no per-event log for them. Phase 4 adds
-- standalone coin events (daily login, daily-goal completion, variant
-- clear, weekly challenge bonus) that need their own dedup window so
-- a user can't farm the same bonus twice in one day / week.
--
-- The log is also useful for the upcoming /api/shop/coin-history view
-- on the profile page so users can see *where* their coins came from.
--
-- Lookup pattern is (user_id, reason, created_at) — index supports
-- the "did this event already fire today?" query.
-- ═══════════════════════════════════════════════════════════════

CREATE TABLE coin_log (
  id         INTEGER PRIMARY KEY,
  user_id    INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  amount     INTEGER NOT NULL,
  reason     TEXT    NOT NULL,
  created_at TEXT    NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX idx_coin_log_user_reason_date ON coin_log(user_id, reason, created_at);
CREATE INDEX idx_coin_log_user_date        ON coin_log(user_id, created_at);
