// Package mapper 数据访问层
package mapper

import (
	"errors"
	"server/config"
	"server/modules/yx/entity"

	"gorm.io/gorm/clause"
)

type YxUserScoreMapper struct{}

func NewYxUserScoreMapper() *YxUserScoreMapper {
	return &YxUserScoreMapper{}
}

func (m *YxUserScoreMapper) FindAll(page, size int) ([]entity.YxUserScore, int64, error) {
	var items []entity.YxUserScore
	var total int64
	config.DB.Model(&entity.YxUserScore{}).Count(&total)
	err := config.DB.Offset((page - 1) * size).Limit(size).Find(&items).Error
	return items, total, err
}

func (m *YxUserScoreMapper) FindByID(id string) (*entity.YxUserScore, error) {
	var item entity.YxUserScore
	err := config.DB.First(&item, "id = ?", id).Error
	return &item, err
}

func (m *YxUserScoreMapper) Create(item *entity.YxUserScore) error {
	return config.DB.Create(item).Error
}

func (m *YxUserScoreMapper) Update(item *entity.YxUserScore) error {
	return config.DB.Save(item).Error
}

func (m *YxUserScoreMapper) UpdateFields(id string, fields map[string]interface{}) error {
	return config.DB.Model(&entity.YxUserScore{}).Where("id = ?", id).Updates(fields).Error
}

func (m *YxUserScoreMapper) UpdateFieldsByMultiCondition(condition *entity.YxUserScore, fields map[string]interface{}) error {
	query := config.DB.Model(&entity.YxUserScore{})

	whereCount := 0 // 记录条件数量，避免无条件更新
	if condition.ID != "" {
		query = query.Where("id = ?", condition.ID)
		whereCount++
	}
	if condition.CreateBy != "" {
		query = query.Where("create_by = ?", condition.CreateBy)
		whereCount++
	}
	if condition.State != "" {
		query = query.Where("state = ?", condition.State)
		whereCount++
	}

	// 安全检查：必须至少有一个查询条件
	if whereCount == 0 {
		return errors.New("至少需要一个查询条件")
	}

	return query.Updates(fields).Error
}

func (m *YxUserScoreMapper) Delete(id string) error {
	return config.DB.Delete(&entity.YxUserScore{}, "id = ?", id).Error
}

func (m *YxUserScoreMapper) BatchCreate(items []entity.YxUserScore, batchSize int) error {
	return config.DB.CreateInBatches(items, batchSize).Error
}

func (m *YxUserScoreMapper) BatchUpdate(items []entity.YxUserScore) error {
	return config.DB.Save(items).Error
}

func (m *YxUserScoreMapper) BatchUpsert(items []entity.YxUserScore, updateColumns []string) error {
	return config.DB.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "id"}},
		DoUpdates: clause.AssignmentColumns(updateColumns),
	}).CreateInBatches(items, 100).Error
}

func (m *YxUserScoreMapper) BatchDelete(ids []string) error {
	return config.DB.Delete(&entity.YxUserScore{}, "id IN ?", ids).Error
}
