-- EXECUTE ONLY AFTER reverting application code and stopping every v2 consumer.
-- Before running, export opportunity_document_link_events and set these session flags:
--   SET clientflow.v2_consumers_active = 'off';
--   SET clientflow.document_ledger_exported = 'on';
BEGIN;

DO $$
BEGIN
  IF current_setting('clientflow.v2_consumers_active', true) IS DISTINCT FROM 'off' THEN
    RAISE EXCEPTION 'rollback refused: confirm all v2 consumers are stopped';
  END IF;
  IF current_setting('clientflow.document_ledger_exported', true) IS DISTINCT FROM 'on' THEN
    RAISE EXCEPTION 'rollback refused: export the reconciliation ledger first';
  END IF;
  IF EXISTS (SELECT 1 FROM commercial_documents
             WHERE opportunity_id IS NULL OR role IS NULL OR is_primary IS NULL OR is_active IS NULL) THEN
    RAISE EXCEPTION 'rollback refused: legacy compatibility fields are incomplete';
  END IF;
END $$;

-- Remove dependent line foreign keys/columns before their target tables.
ALTER TABLE commercial_document_lines DROP CONSTRAINT IF EXISTS commercial_document_lines_opportunity_document_link_id_fkey;
DROP INDEX IF EXISTS idx_document_lines_opportunity_link;
ALTER TABLE commercial_document_lines DROP COLUMN IF EXISTS opportunity_document_link_id;
ALTER TABLE commercial_document_lines DROP CONSTRAINT IF EXISTS ck_commercial_document_lines_document_present;
ALTER TABLE commercial_document_lines DROP CONSTRAINT IF EXISTS commercial_document_lines_commercial_document_id_fkey;
DROP INDEX IF EXISTS idx_document_lines_commercial_document;
ALTER TABLE commercial_document_lines DROP COLUMN IF EXISTS commercial_document_id;

DROP TRIGGER IF EXISTS trg_document_link_events_append_only ON opportunity_document_link_events;
DROP FUNCTION IF EXISTS reject_document_link_event_mutation();
DROP TABLE IF EXISTS opportunity_document_link_events;
DROP TABLE IF EXISTS document_reconciliation_commands;
DROP TABLE IF EXISTS opportunity_document_links;
DELETE FROM schema_migrations WHERE version='007';

COMMIT;
