package app

import (
	"encoding/json"
	"os"
	"path/filepath"
	"testing"

	"bee/audit/internal/schema"
)

func TestAtomicWriteFileReplacesTargetWithoutLeavingTmp(t *testing.T) {
	path := filepath.Join(t.TempDir(), "bee-audit.json")
	if err := os.WriteFile(path, []byte("old\n"), 0644); err != nil {
		t.Fatalf("seed file: %v", err)
	}

	if err := atomicWriteFile(path, []byte("new\n"), 0644); err != nil {
		t.Fatalf("atomicWriteFile: %v", err)
	}

	raw, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read final: %v", err)
	}
	if string(raw) != "new\n" {
		t.Fatalf("final content=%q want %q", string(raw), "new\n")
	}
	if _, err := os.Stat(path + ".tmp"); !os.IsNotExist(err) {
		t.Fatalf("tmp file should be absent after success, err=%v", err)
	}
}

func TestRunRuntimePreflightWritesAtomically(t *testing.T) {
	path := filepath.Join(t.TempDir(), "runtime-health.json")
	a := &App{
		runtime: fakeRuntime{
			collectFn: func(exportDir string) (schema.RuntimeHealth, error) {
				return schema.RuntimeHealth{
					Status:      "OK",
					ExportDir:   exportDir,
					DriverReady: true,
					CUDAReady:   true,
				}, nil
			},
		},
	}

	got, err := a.RunRuntimePreflight("file:" + path)
	if err != nil {
		t.Fatalf("RunRuntimePreflight: %v", err)
	}
	if got != path {
		t.Fatalf("path=%q want %q", got, path)
	}
	if _, err := os.Stat(path + ".tmp"); !os.IsNotExist(err) {
		t.Fatalf("tmp file should be absent after success, err=%v", err)
	}

	raw, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read runtime file: %v", err)
	}
	var health schema.RuntimeHealth
	if err := json.Unmarshal(raw, &health); err != nil {
		t.Fatalf("json unmarshal: %v", err)
	}
	if health.Status != "OK" {
		t.Fatalf("status=%q want OK", health.Status)
	}
}
