
-- Fix items that were created with next_due_at ~= created_at
-- Run this after a backup. Edit the two variables below to widen/narrow the search.

-- CONFIG: adjust as needed
\set LOOKBACK_DAYS 365
\set WINDOW_SECONDS 10

BEGIN;

-- Preview rows to be changed
SELECT id, item_key, course_id, stage, next_due_at, created_at
FROM community.vocab_srs_item
WHERE created_at >= now() - make_interval(days => :LOOKBACK_DAYS)
  AND (
    next_due_at = created_at
    OR abs(EXTRACT(EPOCH FROM (next_due_at - created_at))) <= :WINDOW_SECONDS
  )
ORDER BY created_at ASC
LIMIT 200;

-- Conservative update: set next_due_at to next calendar day at 08:00
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 => :LOOKBACK_DAYS)
  AND (
    next_due_at = created_at
    OR abs(EXTRACT(EPOCH FROM (next_due_at - created_at))) <= :WINDOW_SECONDS
  )
RETURNING id, item_key, course_id, stage, next_due_at, created_at;

COMMIT;

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