-- Plain SQL version of fix-srs-queries.sql for clients that don't support psql meta-commands
-- Configure the two variables below before running (edit them in the file):
--   set lookback_days = 365; set window_seconds = 10;

-- Edit these values as needed
-- Configure the two variables below before running (edit them in the file):
--   set lookback_days = 365; set window_seconds = 10;

-- Preview rows to be changed (edit values in the CTE if needed)
WITH vars AS (
  SELECT 365::int AS lookback_days, 10::int AS window_seconds
)
SELECT id, item_key, course_id, stage, next_due_at, created_at
FROM community.vocab_srs_item
WHERE created_at >= now() - make_interval(days => (SELECT lookback_days FROM vars))
  AND (
    next_due_at = created_at
    OR abs(EXTRACT(EPOCH FROM (next_due_at - created_at))) <= (SELECT window_seconds FROM vars)
  )
ORDER BY created_at ASC
LIMIT 200;

-- Conservative update: set next_due_at to next calendar day at 08:00
WITH vars AS (
  SELECT 365::int AS lookback_days, 10::int AS window_seconds
)
UPDATE community.vocab_srs_item
SET next_due_at = date_trunc('day', created_at + interval '1 day') + interval '8 hours'
WHERE created_at >= now() - make_interval(days => (SELECT lookback_days FROM vars))
  AND (
    next_due_at = created_at
    OR abs(EXTRACT(EPOCH FROM (next_due_at - created_at))) <= (SELECT window_seconds FROM vars)
  )
RETURNING id, item_key, course_id, stage, next_due_at, created_at;

-- After running, re-run `node backend/scripts/diag-srs-stats.js` to validate counts.
