BEGIN;

DO $$
DECLARE
  default_user_id TEXT;
BEGIN
  SELECT id INTO default_user_id FROM app_user ORDER BY username LIMIT 1;
  IF default_user_id IS NULL THEN
    RAISE EXCEPTION 'No app_user rows exist for default_user_id';
  END IF;

  INSERT INTO strategy_run (run_id, user_id, status)
  VALUES ('default_run', default_user_id, 'STOPPED')
  ON CONFLICT (run_id) DO NOTHING;

  UPDATE strategy_log SET user_id = default_user_id, run_id = 'default_run'
    WHERE user_id IS NULL OR run_id IS NULL;
  UPDATE engine_status SET user_id = default_user_id, run_id = 'default_run'
    WHERE user_id IS NULL OR run_id IS NULL;
  UPDATE engine_event SET user_id = default_user_id, run_id = 'default_run'
    WHERE user_id IS NULL OR run_id IS NULL;

  UPDATE paper_broker_account SET user_id = default_user_id, run_id = 'default_run'
    WHERE user_id IS NULL OR run_id IS NULL;
  UPDATE paper_position SET user_id = default_user_id, run_id = 'default_run'
    WHERE user_id IS NULL OR run_id IS NULL;
  UPDATE paper_order SET user_id = default_user_id, run_id = 'default_run'
    WHERE user_id IS NULL OR run_id IS NULL;
  UPDATE paper_trade SET user_id = default_user_id, run_id = 'default_run'
    WHERE user_id IS NULL OR run_id IS NULL;
  UPDATE paper_equity_curve SET user_id = default_user_id, run_id = 'default_run'
    WHERE user_id IS NULL OR run_id IS NULL;

  UPDATE engine_state SET user_id = default_user_id, run_id = 'default_run'
    WHERE user_id IS NULL OR run_id IS NULL;
  UPDATE engine_state_paper SET user_id = default_user_id, run_id = 'default_run'
    WHERE user_id IS NULL OR run_id IS NULL;

  UPDATE mtm_ledger SET user_id = default_user_id, run_id = 'default_run'
    WHERE user_id IS NULL OR run_id IS NULL;
  UPDATE event_ledger SET user_id = default_user_id, run_id = 'default_run'
    WHERE user_id IS NULL OR run_id IS NULL;
END $$;

DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'chk_strategy_run_status') THEN
    ALTER TABLE strategy_run
      ADD CONSTRAINT chk_strategy_run_status
      CHECK (status IN ('RUNNING','STOPPED','ERROR'));
  END IF;
END $$;

DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'uq_paper_order_scope') THEN
    ALTER TABLE paper_order
      ADD CONSTRAINT uq_paper_order_scope UNIQUE (user_id, run_id, id);
  END IF;

  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_paper_trade_order_scope') THEN
    ALTER TABLE paper_trade
      ADD CONSTRAINT fk_paper_trade_order_scope
      FOREIGN KEY (user_id, run_id, order_id)
      REFERENCES paper_order (user_id, run_id, id)
      ON DELETE CASCADE;
  END IF;
END $$;

COMMIT;
