package writer

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

func TestWriteImageCopiesFile(t *testing.T) {
	dir := t.TempDir()
	src := filepath.Join(dir, "src.img")
	dest := filepath.Join(dir, "dest.img")
	content := []byte("metis-test")
	if err := os.WriteFile(src, content, 0o644); err != nil {
		t.Fatalf("write src: %v", err)
	}
	if err := WriteImage(context.Background(), src, dest); err != nil {
		t.Fatalf("write image: %v", err)
	}
	got, err := os.ReadFile(dest)
	if err != nil {
		t.Fatalf("read dest: %v", err)
	}
	if string(got) != string(content) {
		t.Fatalf("expected %q got %q", string(content), string(got))
	}
}

func TestWriteImageWithProgressAndCancel(t *testing.T) {
	dir := t.TempDir()
	src := filepath.Join(dir, "src.img")
	dest := filepath.Join(dir, "dest.img")
	if err := os.WriteFile(src, []byte("metis-progress"), 0o644); err != nil {
		t.Fatalf("write src: %v", err)
	}

	var calls []int64
	if err := WriteImageWithProgress(context.Background(), src, dest, func(written, total int64) {
		calls = append(calls, written)
		if total <= 0 {
			t.Fatalf("unexpected total: %d", total)
		}
	}); err != nil {
		t.Fatalf("WriteImageWithProgress: %v", err)
	}
	if len(calls) == 0 || calls[len(calls)-1] != int64(len("metis-progress")) {
		t.Fatalf("unexpected progress callbacks: %#v", calls)
	}

	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	if err := WriteImageWithProgress(ctx, src, filepath.Join(dir, "cancelled.img"), nil); err == nil {
		t.Fatal("expected cancel error")
	}
}

func TestIsDevicePath(t *testing.T) {
	if !isDevicePath("/dev/sdz") {
		t.Fatal("expected /dev/sdz to be a device path")
	}
	if isDevicePath("/tmp/image.img") {
		t.Fatal("did not expect regular file path to be treated as device")
	}
}

func TestWriteImageErrorBranches(t *testing.T) {
	if err := WriteImageWithProgress(context.Background(), "missing-src", "", nil); err == nil {
		t.Fatal("expected empty destination error before source lookup")
	}
	dir := t.TempDir()
	src := filepath.Join(dir, "src.img")
	if err := os.WriteFile(src, []byte("data"), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := WriteImageWithProgress(context.Background(), src, filepath.Join(dir, "missing", "dest.img"), nil); err != nil {
		t.Fatalf("WriteImageWithProgress nested path: %v", err)
	}
}
