package usecase

import (
	"context"
	"testing"
	"time"

	"apps/backend/internal/module/radar/domain"
	"apps/backend/internal/module/radar/repository"
)

func TestGetTodayGroupsBandsAndExcludesRejected(t *testing.T) {
	ctx := context.Background()
	mem := repository.NewMemory()
	svc := New(mem)
	uid := int64(77)
	now := domain.NowNano()
	start, _ := domain.UTCDayBounds(now)

	if err := mem.SaveServiceProfile(ctx, &domain.ServiceProfile{
		OwnerUID: uid, Services: []domain.ServiceItem{{Name: "水電"}}, UpdatedAt: now,
	}); err != nil {
		t.Fatal(err)
	}
	if err := mem.SaveWatch(ctx, &domain.RadarWatch{
		ID: "w1", OwnerUID: uid, Terms: []string{"水電"}, Status: domain.WatchActive,
		LastSweptAt: now, CreatedAt: now, UpdatedAt: now,
	}); err != nil {
		t.Fatal(err)
	}

	seed := func(id, band, status string, score int) {
		o := &domain.Opportunity{
			ID: id, OwnerUID: uid, ExternalID: id, Permalink: "https://x/" + id,
			AuthorHandle: "u", Text: "需要水電師傅", PostedAt: now - int64(time.Hour),
			Status: status, IntentScore: score, IntentBand: band,
			Reasons: []domain.OpportunityReason{
				{Dimension: domain.DimAuthenticity, Score: 20, Reason: "a"},
				{Dimension: domain.DimIntent, Score: 20, Reason: "i"},
				{Dimension: domain.DimRegion, Score: 20, Reason: "r"},
				{Dimension: domain.DimFreshness, Score: 20, Reason: "f"},
				{Dimension: domain.DimFit, Score: score - 80, Reason: "fit"},
			},
			RegionMatch: domain.RegionUnknown, MatchedTerms: []string{"水電"},
			CreatedAt: start + 1, UpdatedAt: start + 1,
		}
		if _, err := mem.UpsertByExternalID(ctx, o); err != nil {
			t.Fatal(err)
		}
	}
	seed("h1", domain.BandHigh, domain.OppQualified, 85)
	seed("m1", domain.BandMid, domain.OppAccepted, 60)
	seed("l1", domain.BandLow, domain.OppDismissed, 40)
	seed("r1", domain.BandHigh, domain.OppRejected, 10)

	if err := mem.SaveReply(ctx, &domain.ReplyVariant{
		ID: "rp1", OwnerUID: uid, OpportunityID: "h1",
		Variant: domain.ReplyPublicComment, Text: "嗨，可以幫忙。", CreatedAt: now,
	}); err != nil {
		t.Fatal(err)
	}

	got, err := svc.GetToday(ctx, uid)
	if err != nil {
		t.Fatal(err)
	}
	if got.Stats.Total != 3 || got.Stats.High != 1 || got.Stats.Mid != 1 || got.Stats.Low != 1 {
		t.Fatalf("stats = %+v, want total=3 high=1 mid=1 low=1", got.Stats)
	}
	if len(got.High) != 1 || got.High[0].DefaultReply == nil || got.High[0].DefaultReply.Text != "嗨，可以幫忙。" {
		t.Fatalf("high card default reply missing: %+v", got.High)
	}
	if got.EmptyReason != "" {
		t.Fatalf("empty_reason = %q, want empty", got.EmptyReason)
	}
}

func TestGetTodayEmptyNoProfile(t *testing.T) {
	ctx := context.Background()
	svc := New(repository.NewMemory())
	got, err := svc.GetToday(ctx, 9)
	if err != nil {
		t.Fatal(err)
	}
	if got.EmptyReason != "no_watch" {
		t.Fatalf("empty_reason = %q, want no_watch", got.EmptyReason)
	}
}
