-- Add JSONB storage for feature rules without breaking existing TEXT usage

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND tablename = 'feature_rules') THEN
        CREATE TABLE feature_rules (
            id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
            template_id UUID NOT NULL REFERENCES templates(id) ON DELETE CASCADE,
            template_feature_id UUID REFERENCES template_features(id) ON DELETE CASCADE,
            feature_id VARCHAR(100) NOT NULL,
            rule_text TEXT NOT NULL,
            rule_order INTEGER DEFAULT 0,
            created_at TIMESTAMP DEFAULT NOW()
        );

        -- Helpful index to quickly find rules for a feature
        CREATE INDEX IF NOT EXISTS idx_feature_rules_by_template_and_feature
          ON feature_rules (template_id, feature_id, rule_order);
    END IF;
END $$;


