package lotmatch

import (
	"testing"

	"git.mchus.pro/mchus/quoteforge/internal/models"
)

func TestLotResolverPrecedence(t *testing.T) {
	resolver := NewLotResolver(
		[]models.LotPartnumber{
			{Partnumber: "PN-1", LotName: "LOT_A"},
		},
		[]models.Lot{
			{LotName: "CPU_X_LONG"},
			{LotName: "CPU_X"},
		},
	)

	lot, by, err := resolver.Resolve("PN-1")
	if err != nil || lot != "LOT_A" || by != "mapping_table" {
		t.Fatalf("expected mapping_table LOT_A, got lot=%s by=%s err=%v", lot, by, err)
	}

	lot, by, err = resolver.Resolve("CPU_X")
	if err != nil || lot != "CPU_X" || by != "article_exact" {
		t.Fatalf("expected article_exact CPU_X, got lot=%s by=%s err=%v", lot, by, err)
	}

	lot, by, err = resolver.Resolve("CPU_X_LONG_001")
	if err != nil || lot != "CPU_X_LONG" || by != "prefix" {
		t.Fatalf("expected prefix CPU_X_LONG, got lot=%s by=%s err=%v", lot, by, err)
	}
}

func TestMappingMatcherWildcardAndExactLot(t *testing.T) {
	matcher := NewMappingMatcher(
		[]models.LotPartnumber{
			{Partnumber: "R750*", LotName: "SERVER_R750"},
			{Partnumber: "HDD-01", LotName: "HDD_01"},
		},
		[]models.Lot{
			{LotName: "MEM_DDR5_16G_4800"},
		},
	)

	check := func(partnumber string, want string) {
		t.Helper()
		got := matcher.MatchLots(partnumber)
		if len(got) != 1 || got[0] != want {
			t.Fatalf("partnumber %s: expected [%s], got %#v", partnumber, want, got)
		}
	}

	check("R750XD", "SERVER_R750")
	check("HDD-01", "HDD_01")
	check("MEM_DDR5_16G_4800", "MEM_DDR5_16G_4800")

	if got := matcher.MatchLots("UNKNOWN"); len(got) != 0 {
		t.Fatalf("expected no matches for UNKNOWN, got %#v", got)
	}
}
