package main

import (
	"context"
	"path/filepath"
	"testing"
	"time"

	"hamlog/internal/clublog"
	"hamlog/internal/dxcc"
	"hamlog/internal/qso"
)

// Reported from a real import: every ZK2 contact came back as New Zealand and a
// confirmed entity — Niue — disappeared from the operator's DXCC.
//
// cty.dat is not wrong, it is CURRENT: Niue moved to E6, so ZK2 reverted to New
// Zealand there. ClubLog still knows ZK2 was Niue, and knowing that is the whole
// reason for enabling its country file.
func TestClublogPrefixRescuesRetiredPrefixes(t *testing.T) {
	dir := filepath.Join("build", "bin", "data")
	dm := dxcc.NewManager(dir)
	if err := dm.LoadFromDisk(); err != nil {
		t.Skipf("cty.dat not available here: %v", err)
	}
	cm := clublog.NewManager("", dir)
	if err := cm.EnsureLoaded(); err != nil {
		t.Skipf("ClubLog country file not available here: %v", err)
	}
	a := &App{ctx: context.Background(), dxcc: dm, clublog: cm}

	when := time.Date(2005, 6, 1, 0, 0, 0, 0, time.UTC)
	cases := []struct {
		call string
		want int // ADIF entity
		why  string
	}{
		{"ZK2KK", 188, "Niue — the reported case"},
		{"ZK1XYZ", 234, "South Cook Islands, lost the same way"},
	}
	for _, c := range cases {
		q := qso.QSO{Callsign: c.call, QSODate: when}
		if !a.applyClublogException(&q, true) {
			t.Errorf("%s: ClubLog changed nothing (%s)", c.call, c.why)
			continue
		}
		if q.DXCC == nil || *q.DXCC != c.want {
			got := 0
			if q.DXCC != nil {
				got = *q.DXCC
			}
			t.Errorf("%s resolved to %d (%s), want %d — %s", c.call, got, q.Country, c.want, c.why)
		}
	}

	// A callsign ClubLog's prefix table does not know must be left to cty.dat
	// rather than blanked: silence is not an answer.
	q := qso.QSO{Callsign: "E6AG", QSODate: when}
	if a.applyClublogException(&q, true) && q.DXCC != nil && *q.DXCC != 188 {
		t.Errorf("E6AG was moved off Niue, to %d", *q.DXCC)
	}
}
