package commerce

import (
	"context"
	"strings"
)

func (s *Service) AdminBusinessRules(ctx context.Context) ([]map[string]any, error) {
	items, err := s.AdminListSettings(ctx, "")
	if err != nil {
		return nil, err
	}
	out := make([]map[string]any, 0, len(items))
	for _, item := range items {
		key := strings.TrimSpace(stringFromMap(item, "key"))
		if isBusinessRuleSetting(key) {
			out = append(out, item)
		}
	}
	return out, nil
}

func (s *Service) AdminUpdateBusinessRules(ctx context.Context, values map[string]any) ([]map[string]any, error) {
	if values == nil {
		values = map[string]any{}
	}
	for key, value := range values {
		key = strings.TrimSpace(key)
		if key == "" {
			continue
		}
		if !isBusinessRuleSetting(key) {
			return nil, BadRequest("unknown business rule setting: " + key)
		}
		if _, err := s.AdminSetSetting(ctx, key, AdminSettingRequest{Value: value}); err != nil {
			return nil, err
		}
	}
	return s.AdminBusinessRules(ctx)
}

func isBusinessRuleSetting(key string) bool {
	key = strings.TrimSpace(key)
	if key == "" {
		return false
	}
	if strings.HasPrefix(key, "notification.email.") || strings.HasPrefix(key, "notification.sms.") || strings.HasPrefix(key, "payment.") {
		return false
	}
	if strings.HasPrefix(key, "verification.") {
		switch key {
		case "verification.free_quota_per_user", "verification.quota_purchase_enabled", "verification.quota_price_cents":
			return true
		default:
			return false
		}
	}
	return true
}
