package actions

import (
	"fmt"
	"math"
	"zzman/model"

	"gorm.io/gorm"
)

func FindGateways(tx *gorm.DB) ([]model.Gateway, error) {
	var gateways []model.Gateway
	err := tx.Where("enable = 1").Find(&gateways).Error
	if err != nil {
		return nil, err
	}
	return gateways, nil
}

func AppendGatewayConfigVersion(tx *gorm.DB, gateway int) error {
	expr := fmt.Sprintf("if(setid = %d, 1, setid + 1)", math.MaxInt32)
	tx.Model(&model.Gateway{}).
		Where("id = ?", gateway).
		Update("setid", gorm.Expr(expr))
	if tx.Error != nil {
		return fmt.Errorf("更新网关配置版本失败：%w", tx.Error)
	}
	return nil
}
