package actions

import (
	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"zzman/model"
)

const batchSize = 1000

func FindEdgesByCity(tx *gorm.DB, cityId int) ([]model.Edge, error) {
	var edges []model.Edge
	err := tx.Find(&edges, "city_id = ?", cityId).Error
	if err != nil {
		return nil, fmt.Errorf("failed to find edges: %w", err)
	}
	return edges, nil
}

func SliceActiveEdgesByCity(tx *gorm.DB, cityId int, offset int, limit int) ([]model.Edge, error) {
	var edges []model.Edge
	err := tx.Limit(limit).Offset(offset).Find(&edges, "city_id = ? and active = 1", cityId).Error
	if err != nil {
		return nil, fmt.Errorf("failed to find edges with offset: %w", err)
	}
	return edges, nil
}

func SaveEdges(tx *gorm.DB, edges []model.Edge) error {
	if len(edges) == 0 {
		return nil
	}

	// 分批处理边缘设备数据
	for i := 0; i < len(edges); i += batchSize {
		end := i + batchSize
		if end > len(edges) {
			end = len(edges)
		}

		batch := edges[i:end]
		err := tx.Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "macaddr"}},
			UpdateAll: true,
		}).Create(&batch).Error
		if err != nil {
			return fmt.Errorf("failed to save edges batch %d-%d: %w", i, end-1, err)
		}
	}
	return nil
}

func DisableEdgesByMacs(tx *gorm.DB, macs []string) error {
	if len(macs) == 0 {
		return nil
	}

	// 分批处理MAC地址列表
	for i := 0; i < len(macs); i += batchSize {
		end := i + batchSize
		if end > len(macs) {
			end = len(macs)
		}

		batch := macs[i:end]
		err := tx.Model(&model.Edge{}).Where("macaddr IN ?", batch).Update("active", false).Error
		if err != nil {
			return fmt.Errorf("failed to disable edges batch %d-%d: %w", i, end-1, err)
		}
	}
	return nil
}
