package ucca

import "time"

// ============================================================================
// Grouping Methods
// ============================================================================

// GroupByRegulation groups obligations by their regulation ID
func (r *ObligationsRegistry) GroupByRegulation(obligations []Obligation) map[string][]Obligation {
	result := make(map[string][]Obligation)
	for _, obl := range obligations {
		result[obl.RegulationID] = append(result[obl.RegulationID], obl)
	}
	return result
}

// GroupByDeadline groups obligations by deadline timeframe
func (r *ObligationsRegistry) GroupByDeadline(obligations []Obligation) ObligationsByDeadlineResponse {
	result := ObligationsByDeadlineResponse{
		Overdue:     []Obligation{},
		ThisWeek:    []Obligation{},
		ThisMonth:   []Obligation{},
		NextQuarter: []Obligation{},
		Later:       []Obligation{},
		NoDeadline:  []Obligation{},
	}

	now := time.Now()
	oneWeek := now.AddDate(0, 0, 7)
	oneMonth := now.AddDate(0, 1, 0)
	threeMonths := now.AddDate(0, 3, 0)

	for _, obl := range obligations {
		if obl.Deadline == nil || obl.Deadline.Type != DeadlineAbsolute || obl.Deadline.Date == nil {
			result.NoDeadline = append(result.NoDeadline, obl)
			continue
		}

		deadline := *obl.Deadline.Date
		switch {
		case deadline.Before(now):
			result.Overdue = append(result.Overdue, obl)
		case deadline.Before(oneWeek):
			result.ThisWeek = append(result.ThisWeek, obl)
		case deadline.Before(oneMonth):
			result.ThisMonth = append(result.ThisMonth, obl)
		case deadline.Before(threeMonths):
			result.NextQuarter = append(result.NextQuarter, obl)
		default:
			result.Later = append(result.Later, obl)
		}
	}

	return result
}

// GroupByResponsible groups obligations by responsible role
func (r *ObligationsRegistry) GroupByResponsible(obligations []Obligation) map[ResponsibleRole][]Obligation {
	result := make(map[ResponsibleRole][]Obligation)
	for _, obl := range obligations {
		result[obl.Responsible] = append(result[obl.Responsible], obl)
	}
	return result
}

// containsString checks if a slice contains a string
func containsString(slice []string, s string) bool {
	for _, item := range slice {
		if item == s {
			return true
		}
	}
	return false
}
