package service

import (
	"sort"
	"strings"

	"github.com/tidbcloud/aisupport/services/oncall/models"
)

// teamInGroup reports whether the team belongs to the given group (case-insensitive).
// An empty group matches every team (used when no group filter is requested).
func teamInGroup(t models.Team, group string) bool {
	group = strings.TrimSpace(group)
	if group == "" {
		return true
	}
	for _, g := range t.GroupNames {
		if strings.EqualFold(strings.TrimSpace(g), group) {
			return true
		}
	}
	return false
}

// filterTeamsByGroup returns the teams that belong to the given group, preserving
// input order. An empty group returns all teams.
func filterTeamsByGroup(teams []models.Team, group string) []models.Team {
	if strings.TrimSpace(group) == "" {
		return teams
	}
	out := make([]models.Team, 0, len(teams))
	for _, t := range teams {
		if teamInGroup(t, group) {
			out = append(out, t)
		}
	}
	return out
}

// normalizeGroups trims, drops blanks, de-duplicates (case-insensitive, keeping
// first spelling), and defaults to ["Other"] when nothing is left.
func normalizeGroups(groups []string) models.StringList {
	out := make(models.StringList, 0, len(groups))
	seen := make(map[string]bool, len(groups))
	for _, g := range groups {
		g = strings.TrimSpace(g)
		if g == "" {
			continue
		}
		key := strings.ToLower(g)
		if seen[key] {
			continue
		}
		seen[key] = true
		out = append(out, g)
	}
	if len(out) == 0 {
		return models.StringList{"Other"}
	}
	return out
}

// primaryGroup returns the team's first group, or "Other" when it has none.
func primaryGroup(t models.Team) string {
	for _, g := range t.GroupNames {
		if s := strings.TrimSpace(g); s != "" {
			return s
		}
	}
	return "Other"
}

// teamDisplayName returns the display name, falling back to the team key.
func teamDisplayName(t models.Team) string {
	if d := strings.TrimSpace(t.DisplayName); d != "" {
		return d
	}
	return strings.TrimSpace(t.Name)
}

// sortTeamsByPriority orders teams for display: lower SortPriority first
// (ascending, like a "display order"), ties broken by display name then id.
func sortTeamsByPriority(teams []models.Team) {
	sort.SliceStable(teams, func(i, j int) bool {
		if teams[i].SortPriority != teams[j].SortPriority {
			return teams[i].SortPriority < teams[j].SortPriority
		}
		di, dj := teamDisplayName(teams[i]), teamDisplayName(teams[j])
		if di != dj {
			return di < dj
		}
		return teams[i].ID < teams[j].ID
	})
}
