package backtest

import (
	"context"
	"testing"

	"git.toki-labs.com/toki/alt/packages/domain/backtest"
	"git.toki-labs.com/toki/alt/packages/domain/market"
)

func TestBuiltInStrategyPortResolvesKnownStrategy(t *testing.T) {
	port := NewBuiltInStrategyPort()
	strat, err := port.GetStrategy(context.Background(), BuiltInStrategyID)
	if err != nil {
		t.Fatalf("unexpected error resolving built-in strategy: %v", err)
	}
	if strat.ID() != BuiltInStrategyID {
		t.Errorf("strategy id = %q, want %q", strat.ID(), BuiltInStrategyID)
	}
}

func TestBuiltInStrategyPortRejectsUnknownStrategy(t *testing.T) {
	port := NewBuiltInStrategyPort()
	if _, err := port.GetStrategy(context.Background(), "does-not-exist"); err == nil {
		t.Fatal("expected error for unknown strategy id, got nil")
	}
}

func TestBuyAndHoldBuysOnceThenHolds(t *testing.T) {
	port := NewBuiltInStrategyPort()
	strat, err := port.GetStrategy(context.Background(), BuiltInStrategyID)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	instID := market.InstrumentID("KRX:005930")
	cash := market.Price{Currency: market.CurrencyKRW, Amount: market.Decimal{Value: "1000000"}}
	bar := market.Bar{
		InstrumentID: instID,
		Timeframe:    market.TimeframeDaily,
		Close:        market.Price{Currency: market.CurrencyKRW, Amount: market.Decimal{Value: "1000"}},
	}

	// No position yet: the strategy buys a single unit.
	orders, err := strat.Decide(backtest.StrategyInput{Bar: bar, Portfolio: backtest.NewPortfolioState(cash)})
	if err != nil {
		t.Fatalf("unexpected error on first decide: %v", err)
	}
	if len(orders) != 1 {
		t.Fatalf("expected 1 buy order on first bar, got %d", len(orders))
	}
	if orders[0].Side != backtest.OrderSideBuy || orders[0].InstrumentID != instID {
		t.Errorf("unexpected order %+v", orders[0])
	}
	if orders[0].Quantity.Amount.Value != "1" {
		t.Errorf("expected quantity 1, got %s", orders[0].Quantity.Amount.Value)
	}

	// Apply the buy and decide again: with a position held, the strategy holds.
	portfolio, err := backtest.NewPortfolioState(cash).ApplyFill(backtest.Fill{
		InstrumentID: instID,
		Side:         backtest.OrderSideBuy,
		Quantity:     market.Quantity{Amount: market.Decimal{Value: "1"}},
		Price:        bar.Close,
	})
	if err != nil {
		t.Fatalf("failed to apply fill: %v", err)
	}
	held, err := strat.Decide(backtest.StrategyInput{Bar: bar, Portfolio: portfolio})
	if err != nil {
		t.Fatalf("unexpected error on hold decide: %v", err)
	}
	if len(held) != 0 {
		t.Errorf("expected no orders while holding, got %d", len(held))
	}
}
