package m9zApi

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

func useTempFaultHistoryFile(t *testing.T) {
	t.Helper()

	oldFilePath := filePath
	filePath = filepath.Join(t.TempDir(), "data.json")
	t.Cleanup(func() {
		filePath = oldFilePath
	})
}

func TestAddDataSkipsDuplicateFaultWithin12Hours(t *testing.T) {
	useTempFaultHistoryFile(t)

	now := time.Date(2026, 7, 29, 8, 0, 0, 0, time.UTC)
	item := M9zFaultHistory{
		CommUid:   "device-1",
		LoopIdx:   1,
		FaultCode: "01",
		FaultMsg:  "short circuit",
		FaultTime: now,
	}
	if err := addData(item); err != nil {
		t.Fatalf("addData first item error = %v", err)
	}

	duplicate := item
	duplicate.Voltage = 230
	duplicate.FaultTime = now.Add(faultDuplicateWindow - time.Second)
	if err := addData(duplicate); err != nil {
		t.Fatalf("addData duplicate item error = %v", err)
	}

	items, err := readData()
	if err != nil {
		t.Fatalf("readData error = %v", err)
	}
	if len(items) != 1 {
		t.Fatalf("len(items) = %d, want 1", len(items))
	}
	if !items[0].FaultTime.Equal(now) {
		t.Fatalf("FaultTime = %v, want %v", items[0].FaultTime, now)
	}
}

func TestAddDataAllowsDuplicateFaultAfter12Hours(t *testing.T) {
	useTempFaultHistoryFile(t)

	now := time.Date(2026, 7, 29, 8, 0, 0, 0, time.UTC)
	item := M9zFaultHistory{
		CommUid:   "device-1",
		LoopIdx:   1,
		FaultCode: "01",
		FaultMsg:  "short circuit",
		FaultTime: now,
	}
	if err := addData(item); err != nil {
		t.Fatalf("addData first item error = %v", err)
	}

	duplicate := item
	duplicate.FaultTime = now.Add(faultDuplicateWindow)
	if err := addData(duplicate); err != nil {
		t.Fatalf("addData after window error = %v", err)
	}

	items, err := readData()
	if err != nil {
		t.Fatalf("readData error = %v", err)
	}
	if len(items) != 2 {
		t.Fatalf("len(items) = %d, want 2", len(items))
	}
}
