package postgres

import (
	"context"

	"gorm.io/gorm"

	"github.com/break/junhong_cmp_fiber/internal/model"
)

// PollingConcurrencyConfigStore 并发控制配置存储
type PollingConcurrencyConfigStore struct {
	db *gorm.DB
}

// NewPollingConcurrencyConfigStore 创建并发控制配置存储实例
func NewPollingConcurrencyConfigStore(db *gorm.DB) *PollingConcurrencyConfigStore {
	return &PollingConcurrencyConfigStore{db: db}
}

// List 获取所有并发控制配置
func (s *PollingConcurrencyConfigStore) List(ctx context.Context) ([]*model.PollingConcurrencyConfig, error) {
	var configs []*model.PollingConcurrencyConfig
	if err := s.db.WithContext(ctx).Find(&configs).Error; err != nil {
		return nil, err
	}
	return configs, nil
}

// GetByTaskType 根据任务类型获取配置
func (s *PollingConcurrencyConfigStore) GetByTaskType(ctx context.Context, taskType string) (*model.PollingConcurrencyConfig, error) {
	var config model.PollingConcurrencyConfig
	if err := s.db.WithContext(ctx).Where("task_type = ?", taskType).First(&config).Error; err != nil {
		return nil, err
	}
	return &config, nil
}

// Update 更新并发控制配置
func (s *PollingConcurrencyConfigStore) Update(ctx context.Context, config *model.PollingConcurrencyConfig) error {
	return s.db.WithContext(ctx).Save(config).Error
}

// UpdateMaxConcurrency 更新最大并发数
func (s *PollingConcurrencyConfigStore) UpdateMaxConcurrency(ctx context.Context, taskType string, maxConcurrency int, updatedBy uint) error {
	return s.db.WithContext(ctx).Model(&model.PollingConcurrencyConfig{}).
		Where("task_type = ?", taskType).
		Updates(map[string]interface{}{
			"max_concurrency": maxConcurrency,
			"updated_by":      updatedBy,
		}).Error
}
