package emitter

import (
	"strings"
	"testing"

	"git.cloudinit.dev/coreci/orca/internal/jobspec"
)

func TestSystemdEmitter_RestartNever(t *testing.T) {
	spec := &jobspec.WorkloadSpec{
		Kind:    "Job",
		Name:    "one",
		Runtime: &jobspec.RuntimeBlock{OneOf: "process", Command: "/bin/true"},
		Restart: &jobspec.RestartBlock{Mode: "never"},
	}
	files, err := SystemdEmitter{}.Render(spec, &Node{Hostname: "n"})
	if err != nil {
		t.Fatalf("Render: %v", err)
	}
	if !strings.Contains(files[0].Content, "Restart=no") {
		t.Errorf("missing Restart=no:\n%s", files[0].Content)
	}
}

func TestSystemdEmitter_RestartOnFailure(t *testing.T) {
	spec := &jobspec.WorkloadSpec{
		Kind:    "Job",
		Name:    "retry",
		Runtime: &jobspec.RuntimeBlock{OneOf: "process", Command: "/bin/true"},
		Restart: &jobspec.RestartBlock{Mode: "on-failure", MaxRetries: 3, Delay: "5s"},
	}
	files, err := SystemdEmitter{}.Render(spec, &Node{Hostname: "n"})
	if err != nil {
		t.Fatalf("Render: %v", err)
	}
	c := files[0].Content
	if !strings.Contains(c, "Restart=on-failure") {
		t.Errorf("missing Restart=on-failure:\n%s", c)
	}
	if !strings.Contains(c, "StartLimitBurst=3") {
		t.Errorf("missing StartLimitBurst=3:\n%s", c)
	}
	if !strings.Contains(c, "RestartSec=5s") {
		t.Errorf("missing RestartSec=5s:\n%s", c)
	}
	if !strings.Contains(c, "StartLimitIntervalSec=5s") {
		t.Errorf("missing StartLimitIntervalSec=5s:\n%s", c)
	}
}

func TestSystemdEmitter_RestartService(t *testing.T) {
	spec := &jobspec.WorkloadSpec{
		Kind:    "Service",
		Name:    "web",
		Runtime: &jobspec.RuntimeBlock{OneOf: "process", Command: "/bin/httpd"},
		Restart: &jobspec.RestartBlock{Mode: "service", MaxRetries: 5, Delay: "10s"},
	}
	files, err := SystemdEmitter{}.Render(spec, &Node{Hostname: "n"})
	if err != nil {
		t.Fatalf("Render: %v", err)
	}
	c := files[0].Content
	if !strings.Contains(c, "Restart=always") {
		t.Errorf("missing Restart=always:\n%s", c)
	}
	if !strings.Contains(c, "StartLimitBurst=5") {
		t.Errorf("missing StartLimitBurst=5:\n%s", c)
	}
}

func TestSystemdEmitter_RestartNilOmitted(t *testing.T) {
	spec := &jobspec.WorkloadSpec{
		Kind:    "Job",
		Name:    "norest",
		Runtime: &jobspec.RuntimeBlock{OneOf: "process", Command: "/bin/true"},
	}
	files, err := SystemdEmitter{}.Render(spec, &Node{Hostname: "n"})
	if err != nil {
		t.Fatalf("Render: %v", err)
	}
	if strings.Contains(files[0].Content, "Restart=") {
		t.Errorf("nil Restart should omit Restart= line:\n%s", files[0].Content)
	}
}
