package writer

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

func TestWriteImageWithProgressBranches(t *testing.T) {
	dir := t.TempDir()
	src := filepath.Join(dir, "src.img")
	if err := os.WriteFile(src, []byte("writer-test"), 0o644); err != nil {
		t.Fatal(err)
	}
	dest := filepath.Join(dir, "out", "dest.img")
	var calls int
	if err := WriteImageWithProgress(context.Background(), src, dest, func(written, total int64) {
		calls++
		if written == 0 || total == 0 {
			t.Fatalf("unexpected progress: %d/%d", written, total)
		}
	}); err != nil {
		t.Fatalf("WriteImageWithProgress: %v", err)
	}
	if calls == 0 {
		t.Fatal("expected progress callback")
	}
	if got, err := os.ReadFile(dest); err != nil || string(got) != "writer-test" {
		t.Fatalf("write result = %q err=%v", got, err)
	}
	if !isDevicePath("/dev/sdz") || isDevicePath(dest) {
		t.Fatal("isDevicePath helper failed")
	}
	if err := WriteImageWithProgress(context.Background(), src, "", nil); err == nil {
		t.Fatal("expected empty destination error")
	}
	if err := WriteImageWithProgress(context.Background(), filepath.Join(dir, "missing"), dest, nil); err == nil {
		t.Fatal("expected missing source error")
	}
}

func TestCopyFileErrorBranches(t *testing.T) {
	dir := t.TempDir()
	src := filepath.Join(dir, "src.img")
	if err := os.WriteFile(src, []byte("writer-errors"), 0o644); err != nil {
		t.Fatal(err)
	}

	blockedParent := filepath.Join(dir, "blocked-parent")
	if err := os.WriteFile(blockedParent, []byte("not-a-dir"), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := copyFile(context.Background(), src, filepath.Join(blockedParent, "dest.img"), 0, nil); err == nil {
		t.Fatal("expected destination parent mkdir failure")
	}
	if err := copyFile(context.Background(), filepath.Join(dir, "missing.img"), filepath.Join(dir, "dest.img"), 0, nil); err == nil {
		t.Fatal("expected source open failure")
	}
	if err := copyFile(context.Background(), src, dir, 0, nil); err == nil {
		t.Fatal("expected destination create failure")
	}

	sourceDir := filepath.Join(dir, "source-dir")
	if err := os.Mkdir(sourceDir, 0o755); err != nil {
		t.Fatal(err)
	}
	if err := copyFile(context.Background(), sourceDir, filepath.Join(dir, "dir-read.img"), 0, nil); err == nil {
		t.Fatal("expected directory read failure")
	}
	if _, err := os.Stat("/dev/full"); err != nil {
		t.Skip("/dev/full is required for deterministic write-error coverage")
	}
	if err := copyFile(context.Background(), src, "/dev/full", int64(len("writer-errors")), nil); err == nil {
		t.Fatal("expected /dev/full write failure")
	}
}
