package postgres

import (
	"context"

	"gorm.io/gorm"

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

// PollingConfigStore 轮询配置存储
type PollingConfigStore struct {
	db *gorm.DB
}

// NewPollingConfigStore 创建轮询配置存储实例
func NewPollingConfigStore(db *gorm.DB) *PollingConfigStore {
	return &PollingConfigStore{db: db}
}

// Create 创建轮询配置
func (s *PollingConfigStore) Create(ctx context.Context, config *model.PollingConfig) error {
	return s.db.WithContext(ctx).Create(config).Error
}

// GetByID 根据 ID 获取轮询配置
func (s *PollingConfigStore) GetByID(ctx context.Context, id uint) (*model.PollingConfig, error) {
	var config model.PollingConfig
	if err := s.db.WithContext(ctx).First(&config, id).Error; err != nil {
		return nil, err
	}
	return &config, nil
}

// Update 更新轮询配置
func (s *PollingConfigStore) Update(ctx context.Context, config *model.PollingConfig) error {
	return s.db.WithContext(ctx).Save(config).Error
}

// Delete 删除轮询配置
func (s *PollingConfigStore) Delete(ctx context.Context, id uint) error {
	return s.db.WithContext(ctx).Delete(&model.PollingConfig{}, id).Error
}

// List 列表查询轮询配置
func (s *PollingConfigStore) List(ctx context.Context, opts *store.QueryOptions, filters map[string]interface{}) ([]*model.PollingConfig, int64, error) {
	var configs []*model.PollingConfig
	var total int64

	query := s.db.WithContext(ctx).Model(&model.PollingConfig{})

	// 过滤条件
	if status, ok := filters["status"]; ok {
		query = query.Where("status = ?", status)
	}
	if cardCondition, ok := filters["card_condition"].(string); ok && cardCondition != "" {
		query = query.Where("card_condition = ?", cardCondition)
	}
	if cardCategory, ok := filters["card_category"].(string); ok && cardCategory != "" {
		query = query.Where("card_category = ?", cardCategory)
	}
	if carrierID, ok := filters["carrier_id"]; ok {
		query = query.Where("carrier_id = ?", carrierID)
	}
	if configName, ok := filters["config_name"].(string); ok && configName != "" {
		query = query.Where("config_name LIKE ?", "%"+configName+"%")
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页
	if opts == nil {
		opts = store.DefaultQueryOptions()
	}
	offset := (opts.Page - 1) * opts.PageSize
	query = query.Offset(offset).Limit(opts.PageSize)

	// 排序
	if opts.OrderBy != "" {
		query = query.Order(opts.OrderBy)
	} else {
		query = query.Order("priority ASC, id DESC")
	}

	if err := query.Find(&configs).Error; err != nil {
		return nil, 0, err
	}

	return configs, total, nil
}

// ListEnabled 获取所有启用的轮询配置（按优先级排序）
func (s *PollingConfigStore) ListEnabled(ctx context.Context) ([]*model.PollingConfig, error) {
	var configs []*model.PollingConfig
	if err := s.db.WithContext(ctx).
		Where("status = ?", 1).
		Order("priority ASC").
		Find(&configs).Error; err != nil {
		return nil, err
	}
	return configs, nil
}

// GetByName 根据名称获取轮询配置
func (s *PollingConfigStore) GetByName(ctx context.Context, name string) (*model.PollingConfig, error) {
	var config model.PollingConfig
	if err := s.db.WithContext(ctx).Where("config_name = ?", name).First(&config).Error; err != nil {
		return nil, err
	}
	return &config, nil
}

// UpdateStatus 更新配置状态
func (s *PollingConfigStore) UpdateStatus(ctx context.Context, id uint, status int16, updatedBy uint) error {
	return s.db.WithContext(ctx).Model(&model.PollingConfig{}).
		Where("id = ?", id).
		Updates(map[string]interface{}{
			"status":     status,
			"updated_by": updatedBy,
		}).Error
}
