package sales

import (
	"context"
	"errors"
	"testing"

	"github.com/jackc/pgx/v5/pgconn"
	"github.com/shopspring/decimal"
)

var errSalesStockWrite = errors.New("sales stock write failed")

// SetStockQuantity dropped the sqlc :execrows row count, so a reservation or
// deduction could report success while changing no stock. Every caller passes
// row.ID from lockStock (SELECT ... FOR UPDATE, re-locked after EnsureStockRow),
// so zero rows is an integrity failure and is now a hard ErrNotFound — the same
// mapping internal/distribution applies to the identical UpdateSalesStockRow
// query. Non-zero stays a silent pass and the driver error is returned unchanged.
func TestRepositorySetStockQuantityRowCount(t *testing.T) {
	r := &Repository{}
	ctx := context.Background()
	cases := []struct {
		name string
		tag  pgconn.CommandTag
		err  error
		want error // errors.Is target; nil means a silent pass
	}{
		{name: "zero rows is not success", tag: pgconn.NewCommandTag("UPDATE 0"), want: ErrNotFound},
		{name: "one row passes", tag: pgconn.NewCommandTag("UPDATE 1"), want: nil},
		{name: "driver error surfaces unchanged", tag: pgconn.NewCommandTag("UPDATE 0"), err: errSalesStockWrite, want: errSalesStockWrite},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			err := r.SetStockQuantity(ctx, &fakeTx{tag: tc.tag, err: tc.err}, 7,
				decimal.NewFromInt(5), decimal.NewFromInt(2))
			if tc.want == nil {
				if err != nil {
					t.Errorf("SetStockQuantity error = %v, want nil", err)
				}
				return
			}
			if !errors.Is(err, tc.want) {
				t.Errorf("SetStockQuantity error = %v, want %v", err, tc.want)
			}
		})
	}
}
