package usecase

import (
	"context"
	"errors"
	"testing"

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

type productWatchLifecycleStub struct {
	paused int
	err    error
}

func (s *productWatchLifecycleStub) PauseProductWatches(context.Context, int64, string) (int, error) {
	if s.err != nil {
		return 0, s.err
	}
	s.paused++
	return s.paused, nil
}

func TestRemoveProductPausesRadarBeforeDelete(t *testing.T) {
	ctx := context.Background()
	store := repository.NewMemory()
	if err := store.SaveProduct(ctx, &domain.Product{ID: "p1", OwnerUID: 42, BrandID: "b1", Label: "產品"}); err != nil {
		t.Fatal(err)
	}
	bridge := &productWatchLifecycleStub{}
	svc := New(store)
	svc.RadarLifecycle = bridge
	if err := svc.RemoveProduct(ctx, 42, "p1"); err != nil {
		t.Fatal(err)
	}
	if bridge.paused != 1 {
		t.Fatalf("pause bridge calls=%d", bridge.paused)
	}
	if _, err := svc.GetProduct(ctx, 42, "p1"); !errors.Is(err, domain.ErrNotFound) {
		t.Fatalf("product still exists: %v", err)
	}
}

func TestRemoveProductDoesNotDeleteWhenPauseFails(t *testing.T) {
	ctx := context.Background()
	store := repository.NewMemory()
	if err := store.SaveProduct(ctx, &domain.Product{ID: "p1", OwnerUID: 42, BrandID: "b1", Label: "產品"}); err != nil {
		t.Fatal(err)
	}
	svc := New(store)
	svc.RadarLifecycle = &productWatchLifecycleStub{err: errors.New("radar unavailable")}
	if err := svc.RemoveProduct(ctx, 42, "p1"); err == nil {
		t.Fatal("delete succeeded after pause failure")
	}
	if _, err := svc.GetProduct(ctx, 42, "p1"); err != nil {
		t.Fatalf("product should remain for retry: %v", err)
	}
}
