package datascience

import "testing"

func TestDurationStatsFrom(t *testing.T) {
	t.Run("slice vacio retorna estadisticas cero", func(t *testing.T) {
		got := DurationStatsFrom([]int64{})
		if got.N != 0 || got.AvgMs != 0 || got.P50Ms != 0 || got.P90Ms != 0 || got.P99Ms != 0 {
			t.Errorf("got %+v, want zero DurationStats", got)
		}
	})

	t.Run("un solo elemento produce estadisticas identicas", func(t *testing.T) {
		got := DurationStatsFrom([]int64{100})
		if got.N != 1 || got.AvgMs != 100 || got.P50Ms != 100 || got.P90Ms != 100 || got.P99Ms != 100 {
			t.Errorf("got %+v, want all=100", got)
		}
	})

	t.Run("cinco elementos calcula media y percentiles correctos", func(t *testing.T) {
		// sorted: [10,20,30,40,50], n=5
		// P50: idx=int(4*0.5)=2 → 30
		// P90: idx=int(4*0.9)=int(3.6)=3 → 40
		// P99: idx=int(4*0.99)=int(3.96)=3 → 40
		got := DurationStatsFrom([]int64{50, 10, 30, 40, 20})
		if got.N != 5 {
			t.Errorf("N: got %v, want 5", got.N)
		}
		if got.AvgMs != 30 {
			t.Errorf("AvgMs: got %v, want 30", got.AvgMs)
		}
		if got.P50Ms != 30 {
			t.Errorf("P50Ms: got %v, want 30", got.P50Ms)
		}
		if got.P90Ms != 40 {
			t.Errorf("P90Ms: got %v, want 40", got.P90Ms)
		}
		if got.P99Ms != 40 {
			t.Errorf("P99Ms: got %v, want 40", got.P99Ms)
		}
	})

	t.Run("input original no se muta", func(t *testing.T) {
		input := []int64{50, 10, 30}
		_ = DurationStatsFrom(input)
		if input[0] != 50 || input[1] != 10 || input[2] != 30 {
			t.Errorf("input mutated: got %v", input)
		}
	})

	t.Run("diez elementos p90 usa idx truncado", func(t *testing.T) {
		// sorted: [10..100], n=10
		// P50: idx=int(9*0.5)=4 → 50
		// P90: idx=int(9*0.9)=int(8.1)=8 → 90
		got := DurationStatsFrom([]int64{10, 20, 30, 40, 50, 60, 70, 80, 90, 100})
		if got.N != 10 {
			t.Errorf("N: got %v, want 10", got.N)
		}
		if got.AvgMs != 55 {
			t.Errorf("AvgMs: got %v, want 55", got.AvgMs)
		}
		if got.P50Ms != 50 {
			t.Errorf("P50Ms: got %v, want 50", got.P50Ms)
		}
		if got.P90Ms != 90 {
			t.Errorf("P90Ms: got %v, want 90", got.P90Ms)
		}
	})
}
