ALTER TABLE IF EXISTS base_model_catalog
  ADD COLUMN IF NOT EXISTS pricing_rule_set_id uuid REFERENCES model_pricing_rule_sets(id) ON DELETE SET NULL;

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint c
    JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey)
    WHERE c.contype = 'f'
      AND c.conrelid = 'base_model_catalog'::regclass
      AND a.attname = 'pricing_rule_set_id'
  ) THEN
    ALTER TABLE base_model_catalog
      ADD CONSTRAINT fk_base_model_catalog_pricing_rule_set
      FOREIGN KEY (pricing_rule_set_id) REFERENCES model_pricing_rule_sets(id) ON DELETE SET NULL;
  END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_base_model_catalog_pricing_rule_set
  ON base_model_catalog(pricing_rule_set_id);

UPDATE base_model_catalog
SET pricing_rule_set_id = (
  SELECT id FROM model_pricing_rule_sets WHERE rule_set_key = 'default-multimodal-v1' LIMIT 1
)
WHERE pricing_rule_set_id IS NULL
  AND EXISTS (SELECT 1 FROM model_pricing_rule_sets WHERE rule_set_key = 'default-multimodal-v1');
