-- Phase 1 / Migration 3
-- Transaction-safe CHECK constraint expansion for rm_forecast_precomputed
-- Pre-check:
-- SELECT conname, pg_get_constraintdef(oid)
-- FROM pg_constraint
-- WHERE conrelid = 'rm_forecast_precomputed'::regclass AND contype = 'c';
-- Post-check:
-- SELECT conname, pg_get_constraintdef(oid)
-- FROM pg_constraint
-- WHERE conname = 'rm_forecast_precomputed_forecast_type_check';
-- Rollback:
-- BEGIN;
--   DELETE FROM rm_forecast_precomputed WHERE forecast_type IN ('MLB_F5','MLB_RUN_LINE');
--   ALTER TABLE rm_forecast_precomputed DROP CONSTRAINT IF EXISTS rm_forecast_precomputed_forecast_type_check;
--   ALTER TABLE rm_forecast_precomputed ADD CONSTRAINT rm_forecast_precomputed_forecast_type_check
--     CHECK (forecast_type::text = ANY (ARRAY['GAME_MARKETS','TEAM_PROPS','PLAYER_PROP']::text[]));
-- COMMIT;

BEGIN;

ALTER TABLE rm_forecast_precomputed
  DROP CONSTRAINT IF EXISTS rm_forecast_precomputed_forecast_type_check;

ALTER TABLE rm_forecast_precomputed
  ADD CONSTRAINT rm_forecast_precomputed_forecast_type_check
  CHECK (forecast_type::text = ANY (ARRAY['GAME_MARKETS','TEAM_PROPS','PLAYER_PROP','MLB_F5','MLB_RUN_LINE']::text[]));

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'rm_forecast_precomputed_forecast_type_check'
      AND conrelid = 'rm_forecast_precomputed'::regclass
  ) THEN
    RAISE EXCEPTION 'Constraint was not created — aborting';
  END IF;
END $$;

COMMIT;
