package main

import (
	"strings"
	"testing"

	"hamlog/internal/adif"
	"hamlog/internal/qso"
)

// A contact that was not split still has a receive side, and the record
// forwarded to another logger has to carry it: Log4OM reads BAND_RX.
//
// The record UPLOADED to a service must not: in ADIF an absent BAND_RX means
// "same as transmit", and Wavelog shown both draws "17m/17m" on a simplex FT8
// contact — reported by OE6CLD, who had never logged a split QSO in his life.
func TestFillRXDefaults(t *testing.T) {
	hz := int64(14074000)
	q := qso.QSO{Callsign: "F4BPO", Band: "20m", FreqHz: &hz}
	fillRXDefaults(&q)
	if q.BandRX != "20m" {
		t.Errorf("BandRX = %q, want 20m", q.BandRX)
	}
	if q.FreqRXHz == nil || *q.FreqRXHz != hz {
		t.Errorf("FreqRXHz = %v, want %d", q.FreqRXHz, hz)
	}
	// Assert on the RECORD another logger reads, not merely on the struct:
	// both halves of the receive side have to reach it.
	rec := strings.ToUpper(adif.ForwardRecordADIF(q))
	if !strings.Contains(rec, "<BAND_RX:3>20M") {
		t.Errorf("BAND_RX missing from the forwarded record:\n%s", rec)
	}
	if !strings.Contains(rec, "<FREQ_RX:9>14.074000") {
		t.Errorf("FREQ_RX missing from the forwarded record:\n%s", rec)
	}
}

// A genuine split contact keeps what it was given.
func TestFillRXDefaultsKeepsSplit(t *testing.T) {
	tx, rx := int64(14195000), int64(14205000)
	q := qso.QSO{Callsign: "F4BPO", Band: "20m", BandRX: "17m", FreqHz: &tx, FreqRXHz: &rx}
	fillRXDefaults(&q)
	if q.BandRX != "17m" || q.FreqRXHz == nil || *q.FreqRXHz != rx {
		t.Errorf("split QSO was overwritten: band_rx=%q freq_rx=%v", q.BandRX, q.FreqRXHz)
	}
}

// A genuine split contact is uploaded AS split: the rule above is about a
// receive side that repeats the transmit side, not about dropping one.
func TestSplitIsUploadedWithItsReceiveSide(t *testing.T) {
	tx, rx := int64(14195000), int64(18100000)
	q := qso.QSO{Callsign: "F4BPO", Band: "20m", BandRX: "17m", FreqHz: &tx, FreqRXHz: &rx}
	up := strings.ToUpper(adif.SingleRecordADIF(q))
	if !strings.Contains(up, "<BAND_RX:3>17M") || !strings.Contains(up, "<FREQ_RX:9>18.100000") {
		t.Errorf("a cross-band contact lost its receive side:\n%s", up)
	}
}
