package collector

import (
	"path/filepath"
	"testing"

	"bee/audit/internal/schema"
)

func TestEnrichMemoryWithTelemetry(t *testing.T) {
	tmp := t.TempDir()
	oldBase := edacBaseDir
	edacBaseDir = tmp
	t.Cleanup(func() { edacBaseDir = oldBase })

	mustWriteFile(t, filepath.Join(tmp, "mc0", "dimm0", "dimm_label"), "CPU0_DIMM_A1\n")
	mustWriteFile(t, filepath.Join(tmp, "mc0", "dimm0", "dimm_ce_count"), "7\n")
	mustWriteFile(t, filepath.Join(tmp, "mc0", "dimm0", "dimm_ue_count"), "0\n")
	mustWriteFile(t, filepath.Join(tmp, "mc0", "dimm1", "dimm_label"), "CPU1_DIMM_B2\n")
	mustWriteFile(t, filepath.Join(tmp, "mc0", "dimm1", "dimm_ce_count"), "0\n")
	mustWriteFile(t, filepath.Join(tmp, "mc0", "dimm1", "dimm_ue_count"), "2\n")

	doc := sensorsDoc{
		"jc42-i2c-0-18": {
			"CPU0 DIMM A1": map[string]any{"temp1_input": 43.0},
			"CPU1 DIMM B2": map[string]any{"temp2_input": 46.0},
		},
	}

	status := statusOK
	slotA := "CPU0_DIMM_A1"
	slotB := "CPU1_DIMM_B2"
	dimms := []schema.HardwareMemory{
		{Slot: &slotA, HardwareComponentStatus: schema.HardwareComponentStatus{Status: &status}},
		{Slot: &slotB, HardwareComponentStatus: schema.HardwareComponentStatus{Status: &status}},
	}

	got := enrichMemoryWithTelemetry(dimms, doc)

	if got[0].TemperatureC == nil || *got[0].TemperatureC != 43.0 {
		t.Fatalf("dimm0 temperature mismatch: %#v", got[0].TemperatureC)
	}
	if got[0].CorrectableECCErrorCount == nil || *got[0].CorrectableECCErrorCount != 7 {
		t.Fatalf("dimm0 ce mismatch: %#v", got[0].CorrectableECCErrorCount)
	}
	if got[0].Status == nil || *got[0].Status != statusWarning {
		t.Fatalf("dimm0 status mismatch: %#v", got[0].Status)
	}
	if got[1].TemperatureC == nil || *got[1].TemperatureC != 46.0 {
		t.Fatalf("dimm1 temperature mismatch: %#v", got[1].TemperatureC)
	}
	if got[1].UncorrectableECCErrorCount == nil || *got[1].UncorrectableECCErrorCount != 2 {
		t.Fatalf("dimm1 ue mismatch: %#v", got[1].UncorrectableECCErrorCount)
	}
	if got[1].Status == nil || *got[1].Status != statusCritical {
		t.Fatalf("dimm1 status mismatch: %#v", got[1].Status)
	}
	if got[1].DataLossDetected == nil || !*got[1].DataLossDetected {
		t.Fatalf("dimm1 data_loss_detected mismatch: %#v", got[1].DataLossDetected)
	}
}
