package plant

import (
	"errors"
	"sundynix-go/global"
	"sundynix-go/model/plant"
	plantReq "sundynix-go/model/plant/request"

	"gorm.io/gorm"
)

type LevelConfigService struct{}

var LevelConfigServiceApp = new(LevelConfigService)

// AddLevelConfig 添加等级配置
func (s *LevelConfigService) AddLevelConfig(req plantReq.CreateLevelConf) error {
	var exist plant.LevelConfig
	err := global.DB.Where("level = ?", req.Level).First(&exist).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("配置已经存在")
	}
	conf := plant.LevelConfig{
		Level:       req.Level,
		MinSunlight: req.MinSunlight,
		Perks:       req.Perks,
		Title:       req.Title,
	}
	err = global.DB.Create(&conf).Error
	if err != nil {
		return err
	}
	return nil
}

// UpdateLevelConfig 修改等级配置
func (s *LevelConfigService) UpdateLevelConfig(req plantReq.UpdateLevelConf) error {
	updateMap := map[string]interface{}{
		"level":        req.Level,
		"min_sunlight": req.MinSunlight,
		"perks":        req.Perks,
		"title":        req.Title,
	}
	return global.DB.Model(&plant.LevelConfig{}).Where("id = ?", req.Id).Updates(updateMap).Error
}

// LevelConfigList 获取等级配置列表
func (s *LevelConfigService) LevelConfigList() ([]plant.LevelConfig, error) {
	var list []plant.LevelConfig
	err := global.DB.Order("level asc").Find(&list).Error
	return list, err
}

// LevelConfigDetail 获取等级配置详情
func (s *LevelConfigService) LevelConfigDetail(id string) (plant.LevelConfig, error) {
	var config plant.LevelConfig
	err := global.DB.Where("id = ?", id).First(&config).Error
	if err != nil {
		return config, err
	}
	return config, nil
}
