package admin_agent

import (
	"context"
	"sort"

	"jnc-server/app/main/api/internal/svc"
	"jnc-server/app/main/api/internal/types"
	"jnc-server/common/globalkey"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminGetRegionDistributionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminGetRegionDistributionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetRegionDistributionLogic {
	return &AdminGetRegionDistributionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminGetRegionDistributionLogic) AdminGetRegionDistribution() (resp *types.AdminGetRegionDistributionResp, err error) {
	// 1. Query all agents
	builder := l.svcCtx.AgentModel.SelectBuilder()
	builder = builder.Where("del_state = ?", globalkey.DelStateNo)

	agents, err := l.svcCtx.AgentModel.FindAll(l.ctx, builder, "")
	if err != nil {
		return nil, err
	}

	// 2. Group by region in Go
	regionMap := make(map[string]int64)

	for _, agent := range agents {
		region := "未知"
		if agent.Region.Valid && agent.Region.String != "" {
			region = agent.Region.String
		}
		regionMap[region]++
	}

	// 3. Sort by count descending
	type RegionStat struct {
		Region string
		Count  int64
	}

	stats := make([]RegionStat, 0, len(regionMap))
	for region, count := range regionMap {
		stats = append(stats, RegionStat{
			Region: region,
			Count:  count,
		})
	}

	sort.Slice(stats, func(i, j int) bool {
		return stats[i].Count > stats[j].Count
	})

	// 4. Build response
	regions := make([]string, len(stats))
	counts := make([]int64, len(stats))

	for i, stat := range stats {
		regions[i] = stat.Region
		counts[i] = stat.Count
	}

	return &types.AdminGetRegionDistributionResp{
		Regions: regions,
		Counts:  counts,
	}, nil
}
