package server

import (
	"testing"

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

func TestExtractFirmwareComponentAndModel_GPUUsesPartNumberFromParentheses(t *testing.T) {
	component, model := extractFirmwareComponentAndModel("GPU GPUSXM3 (692-2G520-0280-501)")
	if component != "GPU" {
		t.Fatalf("expected component GPU, got %q", component)
	}
	if model != "692-2G520-0280-501" {
		t.Fatalf("expected GPU model 692-2G520-0280-501, got %q", model)
	}
}

func TestExtractFirmwareComponentAndModel_GPUFallbackWithoutParentheses(t *testing.T) {
	component, model := extractFirmwareComponentAndModel("GPU 692-2G520-0280-501")
	if component != "GPU" {
		t.Fatalf("expected component GPU, got %q", component)
	}
	if model != "692-2G520-0280-501" {
		t.Fatalf("expected GPU model 692-2G520-0280-501, got %q", model)
	}
}

func TestBuildFirmwareEntries_IncludesGPUFirmwareFallback(t *testing.T) {
	hw := &models.HardwareConfig{
		Firmware: []models.FirmwareInfo{
			{DeviceName: "BIOS", Version: "1.0.0"},
		},
		GPUs: []models.GPU{
			{
				Slot:       "#CPU0_PCIE2",
				Model:      "GH100 [H200 NVL]",
				PartNumber: "699-2G530-0200-501",
				Firmware:   "96.00.B7.00.02",
			},
			{
				Slot:       "#CPU0_PCIE1",
				Model:      "GH100 [H200 NVL]",
				PartNumber: "699-2G530-0200-501",
				Firmware:   "96.00.B7.00.02",
			},
		},
	}

	entries := buildFirmwareEntries(hw)
	if len(entries) != 2 {
		t.Fatalf("expected 2 deduplicated firmware entries, got %d", len(entries))
	}

	var hasGPU bool
	for _, e := range entries {
		if e.Component == "GPU" && e.Version == "96.00.B7.00.02" {
			hasGPU = true
		}
	}
	if !hasGPU {
		t.Fatalf("expected GPU firmware entry from hardware.gpus fallback")
	}
}

func TestBuildFirmwareEntries_SkipsPlaceholderVersions(t *testing.T) {
	hw := &models.HardwareConfig{
		Firmware: []models.FirmwareInfo{
			{DeviceName: "BMC", Version: "3.13.42P13"},
			{DeviceName: "Front_BP_1", Version: "NA"},
			{DeviceName: "Rear_BP_0", Version: "N/A"},
			{DeviceName: "HDD_BP", Version: "-"},
		},
	}

	entries := buildFirmwareEntries(hw)
	if len(entries) != 1 {
		t.Fatalf("expected only usable firmware entries, got %#v", entries)
	}
	if entries[0].Component != "BMC" || entries[0].Version != "3.13.42P13" {
		t.Fatalf("unexpected remaining firmware entry: %#v", entries[0])
	}
}
