-- Rollback script for LNM-21-102-DEV legacy advisory backfill migration.
-- Removes backfilled observations and linksets by querying the backfill_marker field,
-- then clears the tombstone markers from advisory_raw.
--
-- Usage:
--   psql -d concelier -f ops/devops/tools/ops-scripts/rollback-lnm-backfill.sql
--
-- Environment variables:
--   DRY_RUN - if set to "1", only reports what would be deleted without making changes.
--
-- After running this script, delete the migration record:
--   DELETE FROM schema_migrations WHERE id = '20251127_lnm_legacy_backfill';
--
-- Then restart the Concelier service.

\echo ''
\echo '== LNM-21-102-DEV Backfill Rollback =='
\conninfo

-- Count backfilled observations
SELECT 'Found ' || COUNT(*) || ' backfilled observations to remove.' as status
FROM advisory_observations
WHERE backfill_marker = 'lnm_21_102_dev';

-- Count backfilled linksets
SELECT 'Found ' || COUNT(*) || ' backfilled linksets to remove.' as status
FROM advisory_linksets
WHERE backfill_marker = 'lnm_21_102_dev';

-- Count advisory_raw tombstone markers
SELECT 'Found ' || COUNT(*) || ' advisory_raw documents with tombstone markers to clear.' as status
FROM advisory_raw
WHERE backfill_marker = 'lnm_21_102_dev';

-- Only execute if not DRY_RUN
\if :{?DRY_RUN}
  \echo 'DRY RUN mode - no changes made'
  \echo 'Set DRY_RUN=0 or omit it to execute the rollback'
\else
  -- Step 1: Delete backfilled observations
  DELETE FROM advisory_observations WHERE backfill_marker = 'lnm_21_102_dev';
  \echo 'Deleted observations'

  -- Step 2: Delete backfilled linksets
  DELETE FROM advisory_linksets WHERE backfill_marker = 'lnm_21_102_dev';
  \echo 'Deleted linksets'

  -- Step 3: Clear tombstone markers from advisory_raw
  UPDATE advisory_raw SET backfill_marker = NULL WHERE backfill_marker = 'lnm_21_102_dev';
  \echo 'Cleared tombstone markers'
\endif

\echo ''
\echo '== Rollback Summary =='
\echo ''
\echo 'Next steps:'
\echo '1. Delete the migration record:'
\echo '   DELETE FROM schema_migrations WHERE id = ''20251127_lnm_legacy_backfill'';'
\echo '2. Restart the Concelier service.'
\echo ''
