package store

import (
	"context"
	"testing"
	"time"
)

func TestHostAlwaysOnDefaultAndToggle(t *testing.T) {
	ctx := context.Background()
	st := openTestStore(t)

	h := Host{
		ID: "h-always-on", Name: "lap", OS: "linux", Arch: "amd64",
		ProtocolVersion: 1, EnrolledAt: time.Now().UTC(),
	}
	if err := st.CreateHost(ctx, h, "tok-hash", "pin"); err != nil {
		t.Fatalf("create host: %v", err)
	}
	got, err := st.GetHost(ctx, h.ID)
	if err != nil {
		t.Fatalf("get host: %v", err)
	}
	if !got.AlwaysOn {
		t.Fatalf("new host should default to always_on=true, got false")
	}

	if err := st.SetHostAlwaysOn(ctx, h.ID, false); err != nil {
		t.Fatalf("set always_on: %v", err)
	}
	got, err = st.GetHost(ctx, h.ID)
	if err != nil {
		t.Fatalf("get host 2: %v", err)
	}
	if got.AlwaysOn {
		t.Fatalf("expected always_on=false after toggle, got true")
	}

	hosts, err := st.ListHosts(ctx)
	if err != nil {
		t.Fatalf("list hosts: %v", err)
	}
	if len(hosts) != 1 || hosts[0].AlwaysOn {
		t.Fatalf("ListHosts should report always_on=false, got %+v", hosts)
	}

	// Verify the agent hot-path (LookupHostByAgentToken) also reflects the toggle.
	byToken, err := st.LookupHostByAgentToken(ctx, "tok-hash")
	if err != nil {
		t.Fatalf("lookup by agent token: %v", err)
	}
	if byToken.AlwaysOn {
		t.Fatalf("LookupHostByAgentToken: expected always_on=false after toggle, got true")
	}
}
