package coverart

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

func TestFindSidecar_PrefersCoverJpgOverFolderJpg(t *testing.T) {
	dir := t.TempDir()
	must(t, os.WriteFile(filepath.Join(dir, "folder.jpg"), []byte("f"), 0o644))
	must(t, os.WriteFile(filepath.Join(dir, "cover.jpg"), []byte("c"), 0o644))
	got := FindSidecar(dir)
	want := filepath.Join(dir, "cover.jpg")
	if got != want {
		t.Errorf("got %q, want %q", got, want)
	}
}

func TestFindSidecar_PrefersJpegOverPng(t *testing.T) {
	dir := t.TempDir()
	must(t, os.WriteFile(filepath.Join(dir, "cover.png"), []byte("p"), 0o644))
	must(t, os.WriteFile(filepath.Join(dir, "cover.jpeg"), []byte("j"), 0o644))
	got := FindSidecar(dir)
	want := filepath.Join(dir, "cover.jpeg")
	if got != want {
		t.Errorf("got %q, want %q", got, want)
	}
}

func TestFindSidecar_EmptyDir_ReturnsEmpty(t *testing.T) {
	dir := t.TempDir()
	if got := FindSidecar(dir); got != "" {
		t.Errorf("expected empty string, got %q", got)
	}
}

func TestFindSidecar_DirectoryNamedCoverJpg_Skipped(t *testing.T) {
	dir := t.TempDir()
	must(t, os.MkdirAll(filepath.Join(dir, "cover.jpg"), 0o755))
	must(t, os.WriteFile(filepath.Join(dir, "folder.png"), []byte("p"), 0o644))
	got := FindSidecar(dir)
	want := filepath.Join(dir, "folder.png")
	if got != want {
		t.Errorf("got %q, want %q", got, want)
	}
}

func must(t *testing.T, err error) {
	t.Helper()
	if err != nil {
		t.Fatalf("setup: %v", err)
	}
}
