package geo

import (
	"context"
	"testing"
	"time"

	"go.uber.org/zap"
)

func TestLookupCountryNilSafety(t *testing.T) {
	var s *Service
	if got := s.LookupCountry("8.8.8.8"); got != "" {
		t.Errorf("nil Service LookupCountry = %q, want empty", got)
	}
}

func TestSetLoggerNilSafety(t *testing.T) {
	var s *Service
	s.SetLogger(zap.NewNop())
	s.SetLogger(nil)

	live := &Service{}
	live.SetLogger(nil) // does not panic; falls back to nop logger.
}

func TestDrainNilSafety(t *testing.T) {
	var s *Service
	s.Drain(context.Background())
}

func TestDrainReturnsWhenContextDone(t *testing.T) {
	live := &Service{}
	live.bgCtx, live.bgCancel = context.WithCancel(context.Background())

	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
	defer cancel()

	start := time.Now()
	live.Drain(ctx)
	if elapsed := time.Since(start); elapsed > 5*time.Second {
		t.Fatalf("Drain blocked too long: %s", elapsed)
	}
}

func TestCloseIdempotent(t *testing.T) {
	live := &Service{}
	live.bgCtx, live.bgCancel = context.WithCancel(context.Background())
	if err := live.Close(); err != nil {
		t.Fatalf("first Close: %v", err)
	}
	if err := live.Close(); err != nil {
		t.Fatalf("second Close: %v", err)
	}
	var nilSvc *Service
	if err := nilSvc.Close(); err != nil {
		t.Fatalf("nil Service Close: %v", err)
	}
}
