package client

import (
	"encoding/json"
	"strings"
	"testing"
)

func TestComputePostureScoreNil(t *testing.T) {
	if computePostureScore(nil) != 0 {
		t.Fatal("nil report scores 0")
	}
}

func TestComputePostureScorePerfect(t *testing.T) {
	r := &PostureReport{
		DefenderEnabled: boolPtr(true),
		FirewallDomain:  boolPtr(true),
		SSHListening:    boolPtr(true),
		PatchRecent:     boolPtr(true),
		RebootPending:   boolPtr(false),
		AgentServiceOK:  boolPtr(true),
	}
	if got := computePostureScore(r); got != 100 {
		t.Fatalf("expected 100, got %d", got)
	}
}

func TestComputePostureScoreAVViaProducts(t *testing.T) {
	r := &PostureReport{AVProducts: []string{"ESET"}}
	if got := computePostureScore(r); got < 20 {
		t.Fatalf("AV products should score pillar 1: %d", got)
	}
}

func TestComputePostureScorePartialPatch(t *testing.T) {
	r := &PostureReport{
		PatchRecent:   boolPtr(true),
		RebootPending: boolPtr(true),
	}
	got := computePostureScore(r)
	if got != 10 {
		t.Fatalf("partial patch pillar expected 10, got %d", got)
	}
}

func TestPostureReportJSONSetsScore(t *testing.T) {
	r := &PostureReport{
		DefenderEnabled: boolPtr(true),
		FirewallPublic:  boolPtr(true),
		SSHListening:    boolPtr(true),
		PatchRecent:     boolPtr(true),
		RebootPending:   boolPtr(false),
		AgentServiceOK:  boolPtr(true),
	}
	raw := r.JSON()
	if !strings.Contains(raw, `"posture_score":100`) {
		t.Fatalf("JSON should include computed score: %s", raw)
	}
	var decoded PostureReport
	if err := json.Unmarshal([]byte(raw), &decoded); err != nil {
		t.Fatal(err)
	}
	if decoded.PostureScore != 100 {
		t.Fatalf("decoded score: %d", decoded.PostureScore)
	}
}

func TestBoolPoints(t *testing.T) {
	if boolPoints(nil) != -1 {
		t.Fatal("nil = -1")
	}
	if boolPoints(boolPtr(true)) != 20 {
		t.Fatal("true = 20")
	}
	if boolPoints(boolPtr(false)) != 0 {
		t.Fatal("false = 0")
	}
}

func TestBoolTrueHelper(t *testing.T) {
	if boolTrue(nil) || boolTrue(boolPtr(false)) {
		t.Fatal("boolTrue false cases")
	}
	if !boolTrue(boolPtr(true)) {
		t.Fatal("boolTrue true")
	}
}
