-- Aggregated business rules per (template_id, feature_id)

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.tables 
        WHERE table_schema = 'public' AND table_name = 'feature_business_rules'
    ) THEN
        CREATE TABLE feature_business_rules (
            template_id UUID NOT NULL REFERENCES templates(id) ON DELETE CASCADE,
            feature_id VARCHAR(100) NOT NULL,
            business_rules JSONB NOT NULL,
            updated_at TIMESTAMP DEFAULT NOW(),
            PRIMARY KEY (template_id, feature_id)
        );
        CREATE INDEX IF NOT EXISTS idx_feature_business_rules_t_f ON feature_business_rules (template_id, feature_id);
        CREATE INDEX IF NOT EXISTS idx_feature_business_rules_gin ON feature_business_rules USING GIN (business_rules);
    END IF;
END $$;


