// Filename: internal/repository/group_repository.go
package repository

import (
	"gemini-balancer/internal/models"

	"gorm.io/gorm"
)

func (r *gormGroupRepository) GetGroupByName(name string) (*models.KeyGroup, error) {
	var group models.KeyGroup
	if err := r.db.Where("name = ?", name).First(&group).Error; err != nil {
		return nil, err
	}
	return &group, nil
}

func (r *gormGroupRepository) GetAllGroups() ([]*models.KeyGroup, error) {
	var groups []*models.KeyGroup
	if err := r.db.Order("\"order\" asc, id desc").Find(&groups).Error; err != nil {
		return nil, err
	}
	return groups, nil
}

// 更新group排序
func (r *gormGroupRepository) UpdateOrderInTransaction(orders map[uint]int) error {
	return r.db.Transaction(func(tx *gorm.DB) error {
		for id, order := range orders {
			result := tx.Model(&models.KeyGroup{}).Where("id = ?", id).Update("order", order)
			if result.Error != nil {
				return result.Error
			}
		}
		return nil
	})
}
