package qso

import (
	"testing"
	"time"
)

// "When did I last add an entity" is judged against the whole log. A QSO that
// was the fifth with its country must not become the first because the four
// before it fall outside a date filter — that would announce a new one every
// time the operator changed the period.
func TestLastNewDXCCIgnoresThePeriodFilter(t *testing.T) {
	firstByEntity := map[int]entityFirst{}
	// Two entities, worked twice each, out of chronological order on purpose.
	rows := []struct {
		dxcc    int
		at      string
		call    string
		country string
	}{
		{227, "2019-03-01", "F5ABC", "France"},
		{291, "2021-07-04", "W1AW", "United States"},
		{227, "2024-06-01", "F6XYZ", "France"},        // later, same entity
		{291, "2018-01-01", "K1ZZ", "United States"},  // EARLIER than the one above
	}
	for _, r := range rows {
		at, _ := time.Parse("2006-01-02", r.at)
		if cur, seen := firstByEntity[r.dxcc]; !seen || at.Before(cur.at) {
			firstByEntity[r.dxcc] = entityFirst{at: at, call: r.call, country: r.country}
		}
	}
	if got := firstByEntity[291].call; got != "K1ZZ" {
		t.Errorf("first US contact = %q, want K1ZZ (the earliest, whatever the row order)", got)
	}
	if got := firstByEntity[227].call; got != "F5ABC" {
		t.Errorf("first French contact = %q, want F5ABC", got)
	}

	// The last new entity is the NEWEST of those firsts: France in 2019, not the
	// 2024 French contact, and not the 2021 US one.
	var s Stats
	for num, f := range firstByEntity {
		if f.at.After(parseTimeLoose(s.LastNewDXCCDate)) {
			s.LastNewDXCC, s.LastNewDXCCNum, s.LastNewDXCCCall = f.country, num, f.call
			s.LastNewDXCCDate = f.at.Format(time.RFC3339)
		}
	}
	if s.LastNewDXCC != "France" || s.LastNewDXCCNum != 227 || s.LastNewDXCCCall != "F5ABC" {
		t.Errorf("last new entity = %q/%d/%q, want France/227/F5ABC", s.LastNewDXCC, s.LastNewDXCCNum, s.LastNewDXCCCall)
	}
	if s.LastNewDXCCDate[:10] != "2019-03-01" {
		t.Errorf("date = %q, want 2019-03-01", s.LastNewDXCCDate)
	}
}
