package store

import (
	"io"
	"log"
	"path/filepath"
	"strconv"
	"testing"
)

func newTestStore(t *testing.T) *Store {
	t.Helper()
	s, err := New(filepath.Join(t.TempDir(), "test.db"), log.New(io.Discard, "", 0))
	if err != nil {
		t.Fatalf("store.New: %v", err)
	}
	t.Cleanup(func() { s.Close() })
	return s
}

func TestGuestID(t *testing.T) {
	if got := GuestID("demo-host-01", 100); got != "demo-host-01/100" {
		t.Errorf("GuestID = %q", got)
	}
}

func TestUpsertHost_AndLookup(t *testing.T) {
	s := newTestStore(t)
	if err := s.UpsertHost(&Host{HostID: "h1", CustomerID: "c1", APIKey: "k1"}); err != nil {
		t.Fatalf("UpsertHost: %v", err)
	}
	h, err := s.GetHost("h1")
	if err != nil || h == nil {
		t.Fatalf("GetHost: %v / %v", h, err)
	}
	if h.CustomerID != "c1" || h.APIKey != "k1" || h.DesiredJSON != "{}" || h.LastReportAt != nil {
		t.Errorf("host = %+v", h)
	}
	byKey, err := s.GetHostByAPIKey("k1")
	if err != nil || byKey == nil || byKey.HostID != "h1" {
		t.Errorf("GetHostByAPIKey hit = %+v / %v", byKey, err)
	}
	miss, err := s.GetHostByAPIKey("nope")
	if err != nil || miss != nil {
		t.Errorf("GetHostByAPIKey miss = %+v / %v (want nil,nil)", miss, err)
	}
}

func TestGetHostByCustomer(t *testing.T) {
	s := newTestStore(t)

	// none → nil, nil
	got, err := s.GetHostByCustomer("c1")
	if err != nil || got != nil {
		t.Fatalf("no host: got %+v / %v (want nil,nil)", got, err)
	}

	// one → that host
	if err := s.UpsertHost(&Host{HostID: "c1-aaa111", CustomerID: "c1", APIKey: "k1"}); err != nil {
		t.Fatal(err)
	}
	got, err = s.GetHostByCustomer("c1")
	if err != nil || got == nil || got.HostID != "c1-aaa111" || got.APIKey != "k1" {
		t.Fatalf("one host: got %+v / %v", got, err)
	}

	// two for the same customer → most-recently-updated wins (never a duplicate on reuse).
	// updated_at is second-resolution, so set it explicitly to make the ordering deterministic.
	if err := s.UpsertHost(&Host{HostID: "c1-bbb222", CustomerID: "c1", APIKey: "k2"}); err != nil {
		t.Fatal(err)
	}
	if _, err := s.db.Exec(`UPDATE hosts SET updated_at='2026-01-01 00:00:00' WHERE host_id='c1-aaa111'`); err != nil {
		t.Fatal(err)
	}
	if _, err := s.db.Exec(`UPDATE hosts SET updated_at='2026-06-26 00:00:00' WHERE host_id='c1-bbb222'`); err != nil {
		t.Fatal(err)
	}
	got, err = s.GetHostByCustomer("c1")
	if err != nil || got == nil || got.HostID != "c1-bbb222" {
		t.Fatalf("two hosts: want most-recent c1-bbb222, got %+v / %v", got, err)
	}

	// a different customer is unaffected
	if other, err := s.GetHostByCustomer("c2"); err != nil || other != nil {
		t.Fatalf("other customer: got %+v / %v (want nil,nil)", other, err)
	}
}

// v0.47.0 Host tab: ListHostsByCustomer returns ONLY the customer's hosts, ordered by
// host_id, and leaves other customers' hosts out (isolation).
func TestListHostsByCustomer(t *testing.T) {
	s := newTestStore(t)
	for _, h := range []Host{
		{HostID: "c1-bbb", CustomerID: "c1", APIKey: "k2"},
		{HostID: "c1-aaa", CustomerID: "c1", APIKey: "k1"},
		{HostID: "c2-zzz", CustomerID: "c2", APIKey: "k3"},
	} {
		h := h
		if err := s.UpsertHost(&h); err != nil {
			t.Fatal(err)
		}
	}
	got, err := s.ListHostsByCustomer("c1")
	if err != nil {
		t.Fatalf("ListHostsByCustomer: %v", err)
	}
	if len(got) != 2 || got[0].HostID != "c1-aaa" || got[1].HostID != "c1-bbb" {
		t.Fatalf("c1 hosts = %+v (want [c1-aaa c1-bbb])", got)
	}
	none, err := s.ListHostsByCustomer("c3")
	if err != nil || len(none) != 0 {
		t.Fatalf("c3 hosts = %+v / %v (want empty)", none, err)
	}
}

func TestSaveHostReport_BumpsRealityPreservesIntent(t *testing.T) {
	s := newTestStore(t)
	if err := s.UpsertHost(&Host{HostID: "h1", CustomerID: "c1", APIKey: "k1"}); err != nil {
		t.Fatal(err)
	}
	// Operator-owned intent columns (inert this slice) set out-of-band.
	if _, err := s.db.Exec(`UPDATE hosts SET desired_json='{"want":1}', desired_generation=7 WHERE host_id='h1'`); err != nil {
		t.Fatal(err)
	}

	denorm := HostReportDenorm{AgentVersion: "0.3.0", CPUPercent: 3.2, MemoryPercent: 25, DiskPercent: 19, GuestTotal: 2, GuestRunning: 1, CloudflaredStatus: "active"}
	if err := s.SaveHostReport("h1", "c1", []byte(`{"host_id":"h1"}`), denorm); err != nil {
		t.Fatalf("SaveHostReport: %v", err)
	}

	h, _ := s.GetHost("h1")
	if h.AgentVersion != "0.3.0" || h.LastReportAt == nil {
		t.Errorf("reality not bumped: %+v", h)
	}
	if h.DesiredJSON != `{"want":1}` || h.DesiredGeneration != 7 {
		t.Errorf("a report must NOT clobber intent columns: desired_json=%q gen=%d", h.DesiredJSON, h.DesiredGeneration)
	}
	var n int
	s.db.QueryRow(`SELECT COUNT(*) FROM host_reports WHERE host_id='h1'`).Scan(&n)
	if n != 1 {
		t.Errorf("host_reports rows = %d, want 1", n)
	}
}

func TestUpsertGuestFromReport_PreservesInertColumns(t *testing.T) {
	s := newTestStore(t)
	gid := GuestID("h1", 100)
	if err := s.UpsertGuestFromReport(&Guest{GuestID: gid, CustomerID: "c1", HostID: "h1", VMID: 100, DisplayName: "acme", Status: "running"}); err != nil {
		t.Fatal(err)
	}
	// Slice-10 columns set out-of-band; a report upsert must not touch them.
	if _, err := s.db.Exec(`UPDATE guests SET api_key='controllerkey', desired_spec_json='{"cores":4}' WHERE guest_id=?`, gid); err != nil {
		t.Fatal(err)
	}

	// A later report changes reality (status/name).
	if err := s.UpsertGuestFromReport(&Guest{GuestID: gid, CustomerID: "c1", HostID: "h1", VMID: 100, DisplayName: "acme-renamed", Status: "stopped"}); err != nil {
		t.Fatal(err)
	}

	var apiKey, desiredSpec, status, name string
	err := s.db.QueryRow(`SELECT api_key, desired_spec_json, status, display_name FROM guests WHERE guest_id=?`, gid).
		Scan(&apiKey, &desiredSpec, &status, &name)
	if err != nil {
		t.Fatal(err)
	}
	if apiKey != "controllerkey" || desiredSpec != `{"cores":4}` {
		t.Errorf("inert columns clobbered: api_key=%q desired_spec_json=%q", apiKey, desiredSpec)
	}
	if status != "stopped" || name != "acme-renamed" {
		t.Errorf("reality not updated: status=%q name=%q", status, name)
	}
}

func TestListGuestsForHost(t *testing.T) {
	s := newTestStore(t)

	// none → empty (never nil-error)
	guests, err := s.ListGuestsForHost("h1")
	if err != nil {
		t.Fatalf("ListGuestsForHost (none): %v", err)
	}
	if len(guests) != 0 {
		t.Errorf("no guests → want 0, got %d", len(guests))
	}

	// multiple, inserted out of vmid order → returned ordered by vmid
	for _, vmid := range []int{300, 100, 200} {
		g := &Guest{GuestID: GuestID("h1", vmid), CustomerID: "c1", HostID: "h1", VMID: vmid,
			DisplayName: "g" + strconv.Itoa(vmid), Status: "running", ControllerVersion: "0.87.0"}
		if err := s.UpsertGuestFromReport(g); err != nil {
			t.Fatal(err)
		}
	}
	// a guest on a different host must not leak in
	if err := s.UpsertGuestFromReport(&Guest{GuestID: GuestID("h2", 999), CustomerID: "c2", HostID: "h2", VMID: 999}); err != nil {
		t.Fatal(err)
	}
	// set a secret column to prove the reader never surfaces it
	if _, err := s.db.Exec(`UPDATE guests SET api_key='SECRET' WHERE host_id='h1'`); err != nil {
		t.Fatal(err)
	}

	guests, err = s.ListGuestsForHost("h1")
	if err != nil {
		t.Fatalf("ListGuestsForHost (multi): %v", err)
	}
	if len(guests) != 3 {
		t.Fatalf("want 3 guests for h1, got %d", len(guests))
	}
	wantOrder := []int{100, 200, 300}
	for i, g := range guests {
		if g.VMID != wantOrder[i] {
			t.Errorf("guest[%d].VMID = %d, want %d (vmid order)", i, g.VMID, wantOrder[i])
		}
		if g.ControllerVersion != "0.87.0" || g.Status != "running" {
			t.Errorf("guest[%d] reality wrong: %+v", i, g)
		}
		if g.APIKey != "" {
			t.Errorf("guest[%d] APIKey must not be read, got %q", i, g.APIKey)
		}
	}
}

func TestGetHostStaleness_SkipsNeverReported(t *testing.T) {
	s := newTestStore(t)
	s.UpsertHost(&Host{HostID: "h1", CustomerID: "c1", APIKey: "k1"})
	rows, err := s.GetHostStaleness()
	if err != nil {
		t.Fatal(err)
	}
	if len(rows) != 0 {
		t.Errorf("never-reported host should be skipped, got %d rows", len(rows))
	}
	s.SaveHostReport("h1", "c1", []byte(`{}`), HostReportDenorm{})
	rows, _ = s.GetHostStaleness()
	if len(rows) != 1 || rows[0].HostID != "h1" {
		t.Errorf("after a report expected 1 row, got %+v", rows)
	}
}
