package usecase

import (
	"context"
	"errors"
	"testing"

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

type productSourceFixture struct {
	brand   *ProductBrand
	product *ProductCatalogProduct
}

func (f productSourceFixture) GetBrand(_ context.Context, owner int64, id string) (*ProductBrand, error) {
	if f.brand == nil || f.brand.ID != id {
		return nil, domain.ErrNotFound
	}
	if f.brand.OwnerUID != owner {
		return nil, domain.ErrForbidden
	}
	return f.brand, nil
}
func (f productSourceFixture) GetProduct(_ context.Context, owner int64, id string) (*ProductCatalogProduct, error) {
	if f.product == nil || f.product.ID != id {
		return nil, domain.ErrNotFound
	}
	if f.product.OwnerUID != owner {
		return nil, domain.ErrForbidden
	}
	return f.product, nil
}

func TestLoadProductContextValidatesParentAndSnapshotsVersion(t *testing.T) {
	source := productSourceFixture{brand: &ProductBrand{ID: "b1", OwnerUID: 1, DisplayName: "品牌", UpdatedAt: 10}, product: &ProductCatalogProduct{ID: "p1", BrandID: "b1", OwnerUID: 1, Label: "產品", PainPoints: []string{"漏水"}, UpdatedAt: 20}}
	svc := New(nil)
	svc.ProductSource = source
	snap, err := svc.LoadProductContext(context.Background(), 1, "b1", "p1")
	if err != nil {
		t.Fatal(err)
	}
	source.product.Label = "新版產品"
	if snap.ProductLabel != "產品" || snap.ProductUpdatedAt != 20 {
		t.Fatalf("snapshot changed after source update: %#v", snap)
	}
	if _, err := svc.LoadProductContext(context.Background(), 1, "b1", "missing"); !errors.Is(err, domain.ErrNotFound) {
		t.Fatalf("missing product: %v", err)
	}
	source.product.BrandID = "other"
	if _, err := svc.LoadProductContext(context.Background(), 1, "b1", "p1"); !errors.Is(err, domain.ErrValidation) {
		t.Fatalf("parent mismatch: %v", err)
	}
}
