package service

import (
	"path/filepath"
	"testing"
	"time"
)

func TestRemoteWorkflowErrorBranches(t *testing.T) {
	kube := fakeKubeServer(t)
	installKubeFactory(t, kube)
	app := newTestApp(t)
	app.settings.Namespace = "maintenance"
	app.settings.RunnerImageARM64 = ""

	if _, err := app.RefreshDevices("titan-22"); err == nil {
		t.Fatal("expected RefreshDevices to fail without runner image")
	}

	job := app.newJob("build", "titan-15", "", "")
	app.runBuild(job, false)
	if got := app.job(job.ID); got == nil || got.Status != JobError {
		t.Fatalf("expected build job error, got %#v", got)
	}

	job = app.newJob("flash", "titan-15", "titan-22", "/dev/sdz")
	if err := app.flashArtifact(job.ID, "registry.example/metis/titan-15"); err == nil {
		t.Fatal("expected flashArtifact error")
	}

	app.setJob(job.ID, func(j *Job) {
		j.Status = JobRunning
		j.Stage = "build"
		j.StageStartedAt = time.Now().Add(-30 * time.Second)
	})
	app.heartbeatRemoteJob(job.ID)
	if got := app.job(job.ID); got == nil || got.ProgressPct == 0 {
		t.Fatalf("expected heartbeat progress, got %#v", got)
	}
}

func TestRemoteWorkflowMissingRunnerImageBranch(t *testing.T) {
	kube := fakeKubeServer(t)
	harbor := fakeHarborServer(t, true)
	installKubeFactory(t, kube)
	app := newTestApp(t)
	app.settings.Namespace = "maintenance"
	app.settings.RunnerImageARM64 = ""
	app.settings.HarborAPIBase = harbor.URL + "/api/v2.0"
	app.settings.HarborUsername = "admin"
	app.settings.HarborPassword = "pw"
	app.settings.HarborProject = "metis"
	app.settings.HarborRegistry = "registry.example"
	app.settings.ArtifactStatePath = filepath.Join(t.TempDir(), "artifacts.json")

	job := app.newJob("build", "titan-15", "", "")
	app.runBuild(job, false)
	if got := app.job(job.ID); got == nil || got.Status != JobError {
		t.Fatalf("expected build job error, got %#v", got)
	}
}
