package store

import (
	"context"
	"errors"
	"testing"

	"github.com/tech/sendico/fx/storage/model"
	"github.com/tech/sendico/pkg/db/repository/builder"
	rd "github.com/tech/sendico/pkg/db/repository/decoder"
	"github.com/tech/sendico/pkg/db/storable"
	"github.com/tech/sendico/pkg/merrors"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.uber.org/zap"
)

func TestCurrencyStoreGet(t *testing.T) {
	repo := &repoStub{
		findOneFn: func(_ context.Context, _ builder.Query, result storable.Storable) error {
			currency := result.(*model.Currency)
			currency.Code = "USD"
			return nil
		},
	}
	store := &currencyStore{logger: zap.NewNop(), repo: repo}

	res, err := store.Get(context.Background(), "USD")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if res.Code != "USD" {
		t.Fatalf("unexpected code: %s", res.Code)
	}
}

func TestCurrencyStoreList(t *testing.T) {
	repo := &repoStub{
		findManyFn: func(ctx context.Context, _ builder.Query, decode rd.DecodingFunc) error {
			return runDecoderWithDocs(ctx, t, decode, &model.Currency{Code: "USD"})
		},
	}
	store := &currencyStore{logger: zap.NewNop(), repo: repo}

	currencies, err := store.List(context.Background(), "USD")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(currencies) != 1 || currencies[0].Code != "USD" {
		t.Fatalf("unexpected list result: %+v", currencies)
	}
}

func TestCurrencyStoreUpsertInsert(t *testing.T) {
	inserted := false
	repo := &repoStub{
		findOneFn: func(context.Context, builder.Query, storable.Storable) error {
			return merrors.ErrNoData
		},
		insertFn: func(_ context.Context, obj storable.Storable, _ builder.Query) error {
			_ = cloneCurrency(t, obj)
			inserted = true
			return nil
		},
	}
	store := &currencyStore{logger: zap.NewNop(), repo: repo}

	if err := store.Upsert(context.Background(), &model.Currency{Code: "USD"}); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !inserted {
		t.Fatalf("expected insert to be called")
	}
}

func TestCurrencyStoreGetInvalid(t *testing.T) {
	store := &currencyStore{logger: zap.NewNop(), repo: &repoStub{}}
	if _, err := store.Get(context.Background(), ""); !errors.Is(err, merrors.ErrInvalidArg) {
		t.Fatalf("expected invalid argument error")
	}
}

func TestCurrencyStoreUpsertUpdate(t *testing.T) {
	var updated *model.Currency
	repo := &repoStub{
		findOneFn: func(_ context.Context, _ builder.Query, result storable.Storable) error {
			currency := result.(*model.Currency)
			currency.SetID(bson.NewObjectID())
			currency.Code = "USD"
			return nil
		},
		updateFn: func(_ context.Context, obj storable.Storable) error {
			updated = cloneCurrency(t, obj)
			return nil
		},
	}
	store := &currencyStore{logger: zap.NewNop(), repo: repo}

	if err := store.Upsert(context.Background(), &model.Currency{Code: "USD"}); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if updated == nil || updated.GetID() == nil {
		t.Fatalf("expected update to preserve ID")
	}
}
