package article

import (
	"errors"
	"path/filepath"
	"testing"
	"time"

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

func TestResolveLotCategoriesStrict_MissingCategoryReturnsError(t *testing.T) {
	local, err := localdb.New(filepath.Join(t.TempDir(), "local.db"))
	if err != nil {
		t.Fatalf("init local db: %v", err)
	}
	t.Cleanup(func() { _ = local.Close() })

	if err := local.SaveLocalPricelist(&localdb.LocalPricelist{
		ServerID:  1,
		Source:    "estimate",
		Version:   "S-2026-02-11-001",
		Name:      "test",
		CreatedAt: time.Now(),
		SyncedAt:  time.Now(),
	}); err != nil {
		t.Fatalf("save local pricelist: %v", err)
	}
	localPL, err := local.GetLocalPricelistByServerID(1)
	if err != nil {
		t.Fatalf("get local pricelist: %v", err)
	}
	if err := local.SaveLocalPricelistItems([]localdb.LocalPricelistItem{
		{PricelistID: localPL.ID, LotName: "CPU_A", LotCategory: "", Price: 10},
	}); err != nil {
		t.Fatalf("save local items: %v", err)
	}

	_, err = ResolveLotCategoriesStrict(local, 1, []string{"CPU_A"})
	if err == nil {
		t.Fatalf("expected error")
	}
	if !errors.Is(err, ErrMissingCategoryForLot) {
		t.Fatalf("expected ErrMissingCategoryForLot, got %v", err)
	}
}

func TestResolveLotCategoriesStrict_FallbackToLocalComponents(t *testing.T) {
	local, err := localdb.New(filepath.Join(t.TempDir(), "local.db"))
	if err != nil {
		t.Fatalf("init local db: %v", err)
	}
	t.Cleanup(func() { _ = local.Close() })

	if err := local.SaveLocalPricelist(&localdb.LocalPricelist{
		ServerID:  2,
		Source:    "estimate",
		Version:   "S-2026-02-11-002",
		Name:      "test",
		CreatedAt: time.Now(),
		SyncedAt:  time.Now(),
	}); err != nil {
		t.Fatalf("save local pricelist: %v", err)
	}
	localPL, err := local.GetLocalPricelistByServerID(2)
	if err != nil {
		t.Fatalf("get local pricelist: %v", err)
	}
	if err := local.SaveLocalPricelistItems([]localdb.LocalPricelistItem{
		{PricelistID: localPL.ID, LotName: "CPU_B", LotCategory: "", Price: 10},
	}); err != nil {
		t.Fatalf("save local items: %v", err)
	}
	if err := local.DB().Create(&localdb.LocalComponent{
		LotName:        "CPU_B",
		Category:       "CPU",
		LotDescription: "cpu",
	}).Error; err != nil {
		t.Fatalf("save local components: %v", err)
	}

	cats, err := ResolveLotCategoriesStrict(local, 2, []string{"CPU_B"})
	if err != nil {
		t.Fatalf("expected fallback, got error: %v", err)
	}
	if cats["CPU_B"] != "CPU" {
		t.Fatalf("expected CPU, got %q", cats["CPU_B"])
	}
}

func TestGroupForLotCategory(t *testing.T) {
	if g, ok := GroupForLotCategory("cpu"); !ok || g != GroupCPU {
		t.Fatalf("expected cpu -> GroupCPU")
	}
	if g, ok := GroupForLotCategory("SFP"); ok || g != "" {
		t.Fatalf("expected SFP to be excluded")
	}
}
