package article

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

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

func TestBuild_ParsesNetAndPSU(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: "NIC_2p25G_MCX512A-AC", LotCategory: "NIC", Price: 1},
		{PricelistID: localPL.ID, LotName: "HBA_2pFC32_Gen6", LotCategory: "HBA", Price: 1},
		{PricelistID: localPL.ID, LotName: "PS_1000W_Platinum", LotCategory: "PS", Price: 1},
	}); err != nil {
		t.Fatalf("save local items: %v", err)
	}

	items := models.ConfigItems{
		{LotName: "NIC_2p25G_MCX512A-AC", Quantity: 1},
		{LotName: "HBA_2pFC32_Gen6", Quantity: 1},
		{LotName: "PS_1000W_Platinum", Quantity: 2},
	}
	result, err := Build(local, items, BuildOptions{
		ServerModel:     "DL380GEN11",
		SupportCode:     "1yW",
		ServerPricelist: &localPL.ServerID,
	})
	if err != nil {
		t.Fatalf("build article: %v", err)
	}
	if result.Article == "" {
		t.Fatalf("expected article to be non-empty")
	}
	if contains(result.Article, "UNKNET") || contains(result.Article, "UNKPSU") {
		t.Fatalf("unexpected UNK in article: %s", result.Article)
	}
}

func contains(s, sub string) bool {
	return strings.Contains(s, sub)
}
