package api

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"crypto-miner-server/internal/db"
	"crypto-miner-server/internal/ollama"
)

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

	h := NewAIHandler(database)

	single := ollama.Report{
		AgentID: "agent-1",
		Tool:    "sleep",
		Success: true,
		Output:  "ok",
	}
	body, _ := json.Marshal(single)
	req := httptest.NewRequest(http.MethodPost, "/api/v1/agent/report", bytes.NewReader(body))
	w := httptest.NewRecorder()
	h.HandleReport(w, req)
	if w.Code != http.StatusOK {
		t.Fatalf("single report status %d body %s", w.Code, w.Body.String())
	}

	arr := []ollama.Report{{
		AgentID: "agent-2",
		Tool:    "check_log",
		Success: false,
		Output:  "fail",
	}}
	body, _ = json.Marshal(arr)
	req = httptest.NewRequest(http.MethodPost, "/api/v1/agent/report", bytes.NewReader(body))
	w = httptest.NewRecorder()
	h.HandleReport(w, req)
	if w.Code != http.StatusOK {
		t.Fatalf("array report status %d body %s", w.Code, w.Body.String())
	}

	activity := h.ActivitySnapshot()
	if len(activity) < 2 {
		t.Fatalf("expected activity entries, got %d", len(activity))
	}
}

func TestEstimateXMRPerDay(t *testing.T) {
	out := EstimateXMRPerDay(3_000_000_000)
	xmr, ok := out["xmr_per_day"].(float64)
	if !ok || xmr <= 0 {
		t.Fatalf("expected positive xmr estimate at network hashrate, got %v", out)
	}
}
