package image

import (
	"archive/zip"
	"crypto/sha256"
	"encoding/hex"
	"os"
	"path/filepath"
	"testing"
)

func TestDownloadAndVerifyXZAndZIPBranches(t *testing.T) {
	dir := t.TempDir()
	src := filepath.Join(dir, "src.img")
	if err := os.WriteFile(src, []byte("xz-contents"), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(dir, "xz"), []byte("#!/usr/bin/env bash\nset -eu\nif [[ ${1:-} == -dc ]]; then\n  cat \"$2\"\n  exit 0\nfi\ncp \"${@: -1}\" \"${@: -1}.xz\"\n"), 0o755); err != nil {
		t.Fatal(err)
	}
	t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
	if err := os.WriteFile(src+".xz", []byte("xz-contents"), 0o644); err != nil {
		t.Fatal(err)
	}

	zipPath := filepath.Join(dir, "archive.zip")
	zf, err := os.Create(zipPath)
	if err != nil {
		t.Fatal(err)
	}
	zw := zip.NewWriter(zf)
	w, err := zw.Create("image.img")
	if err != nil {
		t.Fatal(err)
	}
	if _, err := w.Write([]byte("zip-contents")); err != nil {
		t.Fatal(err)
	}
	if err := zw.Close(); err != nil {
		t.Fatal(err)
	}
	if err := zf.Close(); err != nil {
		t.Fatal(err)
	}

	checksum := sha256.Sum256([]byte("xz-contents"))
	if _, err := DownloadAndVerify("file://"+src+".xz", filepath.Join(dir, "out-xz.img"), "sha256:"+hex.EncodeToString(checksum[:])); err != nil {
		t.Fatalf("DownloadAndVerify xz: %v", err)
	}
	if _, err := DownloadAndVerify("file://"+zipPath, filepath.Join(dir, "out-zip.img"), ""); err != nil {
		t.Fatalf("DownloadAndVerify zip: %v", err)
	}
}

func TestDownloadAndVerifyErrorBranches(t *testing.T) {
	dir := t.TempDir()
	if err := VerifyChecksum(filepath.Join(dir, "missing"), "bogus"); err == nil {
		t.Fatal("expected invalid checksum format error")
	}
	if _, err := DownloadAndVerify("file://"+filepath.Join(dir, "missing.img"), filepath.Join(dir, "out.img"), "sha256:deadbeef"); err == nil {
		t.Fatal("expected missing source error")
	}
}
