package exporter

import (
	"bytes"
	"encoding/csv"
	"testing"

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

func TestExportCSV_IncludesAllComponentTypesWithUsableSerials(t *testing.T) {
	result := &models.AnalysisResult{
		FRU: []models.FRUInfo{
			{ProductName: "FRU Board", SerialNumber: "FRU-001", Manufacturer: "ACME"},
		},
		Hardware: &models.HardwareConfig{
			BoardInfo: models.BoardInfo{
				ProductName:  "X12",
				SerialNumber: "BOARD-001",
				Manufacturer: "Supermicro",
			},
			CPUs: []models.CPU{
				{Socket: 0, Model: "Xeon", SerialNumber: "CPU-001"},
			},
			Memory: []models.MemoryDIMM{
				{Slot: "DIMM0", PartNumber: "MEM-PN", SerialNumber: "MEM-001", Manufacturer: "Samsung"},
			},
			Storage: []models.Storage{
				{Slot: "U.2-1", Model: "PM9A3", SerialNumber: "SSD-001", Manufacturer: "Samsung"},
			},
			GPUs: []models.GPU{
				{Slot: "GPU1", Model: "H200", SerialNumber: "GPU-001", Manufacturer: "NVIDIA"},
			},
			PCIeDevices: []models.PCIeDevice{
				{Slot: "PCIe1", DeviceClass: "NVSwitch", SerialNumber: "PCIE-001", Manufacturer: "NVIDIA"},
			},
			NetworkAdapters: []models.NetworkAdapter{
				{Slot: "Slot 17", Location: "#CPU0_PCIE4", Model: "I350", SerialNumber: "NIC-001", Vendor: "Intel"},
				{Slot: "Slot 18", Model: "skip-na", SerialNumber: "N/A", Vendor: "Intel"},
			},
			NetworkCards: []models.NIC{
				{Model: "Legacy NIC", SerialNumber: "LNIC-001"},
			},
			PowerSupply: []models.PSU{
				{Slot: "PSU0", Model: "GW-CRPS3000LW", SerialNumber: "PSU-001", Vendor: "Great Wall"},
			},
		},
	}

	var buf bytes.Buffer
	if err := New(result).ExportCSV(&buf); err != nil {
		t.Fatalf("ExportCSV failed: %v", err)
	}

	rows, err := csv.NewReader(bytes.NewReader(buf.Bytes())).ReadAll()
	if err != nil {
		t.Fatalf("read csv: %v", err)
	}
	if len(rows) < 2 {
		t.Fatalf("expected data rows, got %d", len(rows))
	}

	serials := make(map[string]bool)
	for _, row := range rows[1:] {
		if len(row) > 1 {
			serials[row[1]] = true
		}
	}

	want := []string{"FRU-001", "BOARD-001", "CPU-001", "MEM-001", "SSD-001", "GPU-001", "PCIE-001", "NIC-001", "LNIC-001", "PSU-001"}
	for _, sn := range want {
		if !serials[sn] {
			t.Fatalf("expected serial %s in csv export", sn)
		}
	}
	if serials["N/A"] {
		t.Fatalf("did not expect unusable serial N/A in export")
	}
}
