package server

import (
	"strings"
	"testing"
)

func TestJobManagerCreateGetUpdateCancel(t *testing.T) {
	manager := NewJobManager()

	req := CollectRequest{
		Host:     "bmc01.local",
		Protocol: "redfish",
		Port:     443,
		Username: "admin",
		AuthType: "password",
		Password: "top-secret",
		TLSMode:  "strict",
	}

	job := manager.CreateJob(req)
	if job == nil {
		t.Fatalf("expected created job")
	}
	if job.Status != CollectStatusQueued {
		t.Fatalf("expected queued status, got %q", job.Status)
	}
	if job.Progress != 0 {
		t.Fatalf("expected progress 0, got %d", job.Progress)
	}
	if job.RequestMeta.Host != req.Host {
		t.Fatalf("expected host in request meta")
	}
	if strings.Contains(strings.Join(job.Logs, " "), req.Password) {
		t.Fatalf("password leaked in logs")
	}

	got, ok := manager.GetJob(job.ID)
	if !ok {
		t.Fatalf("expected job to exist")
	}
	if got.ID != job.ID {
		t.Fatalf("wrong job id")
	}

	updated, ok := manager.UpdateJobStatus(job.ID, CollectStatusRunning, 42, "")
	if !ok {
		t.Fatalf("expected update to succeed")
	}
	if updated.Status != CollectStatusRunning || updated.Progress != 42 {
		t.Fatalf("unexpected update snapshot: %+v", updated)
	}

	withLog, ok := manager.AppendJobLog(job.ID, "Сбор инвентаря...")
	if !ok {
		t.Fatalf("expected append to succeed")
	}
	if len(withLog.Logs) < 2 {
		t.Fatalf("expected additional log, got %v", withLog.Logs)
	}

	canceled, ok := manager.CancelJob(job.ID)
	if !ok {
		t.Fatalf("expected cancel to succeed")
	}
	if canceled.Status != CollectStatusCanceled {
		t.Fatalf("expected canceled status, got %q", canceled.Status)
	}

	canceledAgain, ok := manager.CancelJob(job.ID)
	if !ok {
		t.Fatalf("expected repeated cancel to succeed")
	}
	if canceledAgain.Status != CollectStatusCanceled {
		t.Fatalf("expected canceled status after repeated cancel")
	}
}
