package api

import (
	"os"
	"path/filepath"
	"runtime"
	"testing"
)

// TestWriteConfig0600 asserts F8: controller.yaml is persisted 0600 (it holds infra secrets), even when
// the target file already existed with looser (0644) permissions. POSIX modes only — skipped on Windows.
func TestWriteConfig0600(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("POSIX file modes not represented on Windows")
	}
	dir := t.TempDir()
	path := filepath.Join(dir, "controller.yaml")

	// Pre-create with world-readable 0644 to prove the helper tightens an existing file.
	if err := os.WriteFile(path, []byte("old: true\n"), 0o644); err != nil {
		t.Fatal(err)
	}

	if err := writeConfig0600(path, []byte("hub:\n  api_key: redacted\n")); err != nil {
		t.Fatalf("writeConfig0600: %v", err)
	}

	fi, err := os.Stat(path)
	if err != nil {
		t.Fatal(err)
	}
	if mode := fi.Mode().Perm(); mode != 0o600 {
		t.Fatalf("config mode = %o, want 0600", mode)
	}
	// No leftover temp file.
	if _, err := os.Stat(path + ".tmp"); !os.IsNotExist(err) {
		t.Fatalf("temp file not cleaned up")
	}
}
