package worker_test

import (
	"os"
	"path/filepath"
	"testing"

	"github.com/jfraeys/fetch_ml/internal/worker"
)

func TestStageSnapshot_NoSnapshotID(t *testing.T) {
	base := t.TempDir()
	jobDir := filepath.Join(base, "job")
	if err := os.MkdirAll(jobDir, 0750); err != nil {
		t.Fatalf("mkdir: %v", err)
	}
	if err := worker.StageSnapshot(base, filepath.Join(base, "data"), "t1", "", jobDir); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if _, err := os.Stat(filepath.Join(jobDir, "snapshot")); err == nil {
		t.Fatalf("expected no snapshot dir")
	}
}

func TestStageSnapshot_UsesPrewarmDirWhenPresent(t *testing.T) {
	base := t.TempDir()
	dataDir := filepath.Join(base, "data")
	jobDir := filepath.Join(base, "job")
	if err := os.MkdirAll(jobDir, 0750); err != nil {
		t.Fatalf("mkdir: %v", err)
	}
	prewarmSrc := filepath.Join(base, ".prewarm", "snapshots", "t1")
	if err := os.MkdirAll(prewarmSrc, 0750); err != nil {
		t.Fatalf("mkdir prewarm: %v", err)
	}
	if err := os.WriteFile(filepath.Join(prewarmSrc, "file.txt"), []byte("ok"), 0600); err != nil {
		t.Fatalf("write: %v", err)
	}

	if err := worker.StageSnapshot(base, dataDir, "t1", "snap-1", jobDir); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	if _, err := os.Stat(prewarmSrc); err == nil {
		t.Fatalf("expected prewarm dir to be moved away")
	}
	b, err := os.ReadFile(filepath.Join(jobDir, "snapshot", "file.txt"))
	if err != nil {
		t.Fatalf("read: %v", err)
	}
	if string(b) != "ok" {
		t.Fatalf("unexpected contents: %q", string(b))
	}
}

func TestStageSnapshot_FallsBackToDataDirCopy(t *testing.T) {
	base := t.TempDir()
	dataDir := filepath.Join(base, "data")
	jobDir := filepath.Join(base, "job")
	if err := os.MkdirAll(jobDir, 0750); err != nil {
		t.Fatalf("mkdir: %v", err)
	}
	src := filepath.Join(dataDir, "snapshots", "snap-1")
	if err := os.MkdirAll(src, 0750); err != nil {
		t.Fatalf("mkdir src: %v", err)
	}
	if err := os.WriteFile(filepath.Join(src, "file.txt"), []byte("ok"), 0600); err != nil {
		t.Fatalf("write: %v", err)
	}

	if err := worker.StageSnapshot(base, dataDir, "t1", "snap-1", jobDir); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	b, err := os.ReadFile(filepath.Join(jobDir, "snapshot", "file.txt"))
	if err != nil {
		t.Fatalf("read: %v", err)
	}
	if string(b) != "ok" {
		t.Fatalf("unexpected contents: %q", string(b))
	}
}

func TestStageSnapshot_RejectsInvalidSnapshotID(t *testing.T) {
	base := t.TempDir()
	jobDir := filepath.Join(base, "job")
	if err := os.MkdirAll(jobDir, 0750); err != nil {
		t.Fatalf("mkdir: %v", err)
	}
	if err := worker.StageSnapshot(base, filepath.Join(base, "data"), "t1", "bad/name", jobDir); err == nil {
		t.Fatalf("expected error")
	}
}
