package config

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

func TestNormalizeControllerInput(t *testing.T) {
	tests := []struct {
		in   string
		want string
	}{
		{"", DefaultControllerInput},
		{"   ", DefaultControllerInput},
		{" ipv4.uk ", "ipv4.uk"},
		{"https://ctrl.example.com", "https://ctrl.example.com"},
	}

	for _, tt := range tests {
		if got := NormalizeControllerInput(tt.in); got != tt.want {
			t.Fatalf("NormalizeControllerInput(%q) = %q, want %q", tt.in, got, tt.want)
		}
	}
}

func TestControlURLForControllerInput(t *testing.T) {
	tests := []struct {
		in   string
		want string
	}{
		{"", DefaultControlURL},
		{"ipv4.uk", "https://sdp.ipv4.uk"},
		{"example.com", "https://sdp.example.com"},
		{"https://ctrl.example.com", "https://ctrl.example.com"},
		{"http://ctrl.example.com", "http://ctrl.example.com"},
	}

	for _, tt := range tests {
		if got := ControlURLForControllerInput(tt.in); got != tt.want {
			t.Fatalf("ControlURLForControllerInput(%q) = %q, want %q", tt.in, got, tt.want)
		}
	}
}

func TestDefaultPath(t *testing.T) {
	got := DefaultPath(`C:\ProgramData`)
	want := filepath.Join(`C:\ProgramData`, "Mirage", "mirage-ui.json")
	if got != want {
		t.Fatalf("DefaultPath() = %q, want %q", got, want)
	}
}

func TestStoreRoundTrip(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "mirage-ui.json")

	want := State{
		ControllerInput: "ipv4.uk",
		AuthKey:         "tskey-auth-k123",
	}
	if err := Save(path, want); err != nil {
		t.Fatalf("Save() error = %v", err)
	}

	got, err := Load(path)
	if err != nil {
		t.Fatalf("Load() error = %v", err)
	}
	if got != want {
		t.Fatalf("Load() = %#v, want %#v", got, want)
	}
}

func TestLoadMissingFileReturnsZeroState(t *testing.T) {
	path := filepath.Join(t.TempDir(), "missing.json")
	got, err := Load(path)
	if err != nil {
		t.Fatalf("Load() error = %v", err)
	}
	if got != (State{}) {
		t.Fatalf("Load() = %#v, want zero state", got)
	}
}

func TestSaveCreatesParentDirectory(t *testing.T) {
	path := filepath.Join(t.TempDir(), "nested", "mirage-ui.json")
	if err := Save(path, State{ControllerInput: "ipv4.uk"}); err != nil {
		t.Fatalf("Save() error = %v", err)
	}
	if _, err := os.Stat(path); err != nil {
		t.Fatalf("saved file stat error = %v", err)
	}
}
