-- Migration: Add activity tracking to sessions for grace-period cleanup
-- Sessions with recent activity survive cleanup even if past expires_at

ALTER TABLE sessions ADD COLUMN last_activity_at TIMESTAMPTZ;
UPDATE sessions SET last_activity_at = created_at WHERE last_activity_at IS NULL;
ALTER TABLE sessions ALTER COLUMN last_activity_at SET NOT NULL;

-- Replace simple expires index with composite index for cleanup queries
DROP INDEX IF EXISTS idx_sessions_expires;
CREATE INDEX idx_sessions_cleanup ON sessions(status, expires_at, last_activity_at) WHERE status = 'active';
