// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package handlers

import (
	"sort"
	"strconv"

	"github.com/gin-gonic/gin"
	"wa-assistant/backend/database"
	"wa-assistant/backend/models"
)

// Additional senders follow the same tenant and staff assignments as the primary.
func validateRotationAgent(c *gin.Context, agentID uint) bool {
	query := database.DB.Model(&models.Agent{}).Where("id = ? AND tenant_id = ?", agentID, currentTenantID(c))
	if !isTenantAdmin(c) {
		query = query.Where("id IN (?)", database.DB.Model(&models.UserAgentAssignment{}).
			Select("agent_id").Where("tenant_id = ? AND user_id = ?", currentTenantID(c), currentUserID(c)))
	}
	var count int64
	if err := query.Count(&count).Error; err != nil {
		c.JSON(500, gin.H{"error": "Belum bisa memeriksa akses nomor pengirim"})
		return false
	}
	if count == 0 {
		c.JSON(403, gin.H{"error": "Ada nomor pengirim yang tidak tersedia untuk akun Anda"})
		return false
	}
	return true
}

type broadcastReassignment struct {
	RecipientID uint
	FromAgentID uint
	AgentID     uint
}

// Both the preview and the worker use this planner. Existing healthy assignments
// stay in place, and only pending recipients can move to the least loaded sender.
func planBroadcastReassignment(recipients []models.BroadcastRecipient, healthy []uint) []broadcastReassignment {
	if len(healthy) == 0 {
		return nil
	}
	healthySet := make(map[uint]bool, len(healthy))
	load := make(map[uint]int, len(healthy))
	for _, id := range healthy {
		healthySet[id] = true
	}
	var pending []models.BroadcastRecipient
	for _, r := range recipients {
		if r.Status != "pending" {
			continue
		}
		if healthySet[r.AgentID] {
			load[r.AgentID]++
		} else {
			pending = append(pending, r)
		}
	}
	sort.Slice(pending, func(i, j int) bool {
		if pending[i].Number == pending[j].Number {
			return pending[i].ID < pending[j].ID
		}
		return pending[i].Number < pending[j].Number
	})
	moves := make([]broadcastReassignment, 0, len(pending))
	for _, r := range pending {
		dest := pickFailoverAgent(r.Number, healthy, load)
		moves = append(moves, broadcastReassignment{RecipientID: r.ID, FromAgentID: r.AgentID, AgentID: dest})
		load[dest]++
	}
	return moves
}

func rotationSimulationCounts(pool []uint, sampleSize int) (map[uint]int, map[uint]int, int) {
	initial, after := map[uint]int{}, map[uint]int{}
	if len(pool) < 2 {
		return initial, after, 0
	}
	recipients := make([]models.BroadcastRecipient, 0, sampleSize)
	for i := 0; i < sampleSize; i++ {
		number := "628000" + strconv.Itoa(100000+i)
		assigned := stickyAgent(number, pool)
		initial[assigned]++
		after[assigned]++
		recipients = append(recipients, models.BroadcastRecipient{ID: uint(i + 1), Number: number, AgentID: assigned, Status: "pending"})
	}
	moves := planBroadcastReassignment(recipients, pool[1:])
	for _, m := range moves {
		after[m.FromAgentID]--
		after[m.AgentID]++
	}
	return initial, after, len(moves)
}
