package offlineq

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

	"hamlog/internal/qso"
)

// The outbox is the ONLY copy of a QSO logged while the database was down, so the
// round-trip must be lossless: append → read back identical (callsign, band, mode,
// date) and each record must carry a queue id (what makes the replay idempotent).
func TestQueueRoundTrip(t *testing.T) {
	dir := t.TempDir()
	q := New(dir)

	if n := q.Count(); n != 0 {
		t.Fatalf("fresh queue: count = %d, want 0", n)
	}

	mk := func(call, band, mode string) qso.QSO {
		return qso.QSO{
			Callsign: call, Band: band, Mode: mode,
			QSODate: time.Date(2026, 7, 10, 12, 34, 0, 0, time.UTC),
		}
	}
	id1, err := q.Append(mk("K1ABC", "20m", "SSB"))
	if err != nil {
		t.Fatalf("append 1: %v", err)
	}
	id2, err := q.Append(mk("DL1XYZ", "40m", "CW"))
	if err != nil {
		t.Fatalf("append 2: %v", err)
	}
	if id1 == "" || id2 == "" || id1 == id2 {
		t.Fatalf("queue ids must be non-empty and distinct: %q / %q", id1, id2)
	}

	pending, err := q.Pending()
	if err != nil {
		t.Fatalf("pending: %v", err)
	}
	if len(pending) != 2 {
		t.Fatalf("pending = %d, want 2", len(pending))
	}
	if pending[0].Callsign != "K1ABC" || pending[0].Band != "20m" || pending[0].Mode != "SSB" {
		t.Errorf("record 1 round-tripped wrong: %+v", pending[0])
	}
	if pending[1].Callsign != "DL1XYZ" || pending[1].Mode != "CW" {
		t.Errorf("record 2 round-tripped wrong: %+v", pending[1])
	}
	// The queue id must survive the ADIF round-trip — without it the replay
	// can't be idempotent and a crash would duplicate contacts.
	for i, p := range pending {
		if p.Extras[qso.OfflineQueueKey] == "" {
			t.Errorf("record %d lost its %s extra", i, qso.OfflineQueueKey)
		}
	}

	// Archive keeps a copy BEFORE we clear anything.
	arch, err := q.Archive()
	if err != nil || arch == "" {
		t.Fatalf("archive: %v (path %q)", err, arch)
	}
	if _, err := os.Stat(arch); err != nil {
		t.Fatalf("archive file missing: %v", err)
	}

	// Partial replay: the first QSO went in, the second failed → keep only it.
	if err := q.Rewrite(pending[1:]); err != nil {
		t.Fatalf("rewrite: %v", err)
	}
	left, err := q.Pending()
	if err != nil {
		t.Fatalf("pending after rewrite: %v", err)
	}
	if len(left) != 1 || left[0].Callsign != "DL1XYZ" {
		t.Fatalf("after rewrite: got %d records (%v), want just DL1XYZ", len(left), left)
	}

	// Everything replayed → the outbox is removed (the archive still holds it).
	if err := q.Rewrite(nil); err != nil {
		t.Fatalf("rewrite empty: %v", err)
	}
	if _, err := os.Stat(filepath.Join(dir, FileName)); !os.IsNotExist(err) {
		t.Errorf("outbox should be gone once fully replayed, stat err = %v", err)
	}
	if n := q.Count(); n != 0 {
		t.Errorf("count after full replay = %d, want 0", n)
	}
}
