package db

import (
	"testing"
	"time"

	"crypto-miner-server/internal/models"
)

func TestAgentCRUD(t *testing.T) {
	d, err := New(t.TempDir())
	if err != nil {
		t.Fatal(err)
	}
	defer d.Close()

	agent := &models.Agent{
		ID:       "agent-test-001",
		Name:     "lab-pc",
		Wallet:   "48abc",
		IP:       "192.168.1.50",
		Version:  "1.0",
		Status:   "online",
		CPUCores: 8,
		MemoryGB: 16,
		LastSeen: time.Now(),
	}
	if err := d.UpsertAgent(agent); err != nil {
		t.Fatalf("upsert: %v", err)
	}

	got, err := d.GetAgent(agent.ID)
	if err != nil {
		t.Fatalf("get: %v", err)
	}
	if got.Name != "lab-pc" {
		t.Fatalf("name mismatch: %q", got.Name)
	}

	list, err := d.ListAgents()
	if err != nil {
		t.Fatal(err)
	}
	if len(list) != 1 {
		t.Fatalf("expected 1 agent, got %d", len(list))
	}

	if err := d.UpdateAgentMeta(agent.ID, "notes here", []string{"lab", "gpu"}); err != nil {
		t.Fatal(err)
	}
	got, _ = d.GetAgent(agent.ID)
	if got.Notes != "notes here" || len(got.Tags) != 2 {
		t.Fatalf("meta not saved: notes=%q tags=%v", got.Notes, got.Tags)
	}
}

func TestGetFleetStatsEmpty(t *testing.T) {
	d, err := New(t.TempDir())
	if err != nil {
		t.Fatal(err)
	}
	defer d.Close()

	stats, err := d.GetFleetStats()
	if err != nil {
		t.Fatal(err)
	}
	if stats.TotalAgents != 0 {
		t.Fatalf("expected 0 agents, got %d", stats.TotalAgents)
	}
}
