package builder

import (
	"encoding/base64"
	"io"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func decryptMediaForTest(encPath string, key []byte, outPath string) error {
	in, err := os.Open(encPath)
	if err != nil {
		return err
	}
	defer in.Close()
	head := make([]byte, len(mediaLockMagic))
	if _, err := io.ReadFull(in, head); err != nil || string(head) != mediaLockMagic {
		return err
	}
	out, err := os.Create(outPath)
	if err != nil {
		return err
	}
	defer out.Close()
	buf := make([]byte, 256*1024)
	ki := 0
	for {
		n, readErr := in.Read(buf)
		if n > 0 {
			plain := make([]byte, n)
			for i := 0; i < n; i++ {
				plain[i] = buf[i] ^ key[ki%len(key)]
				ki++
			}
			if _, err := out.Write(plain); err != nil {
				return err
			}
		}
		if readErr == io.EOF {
			break
		}
		if readErr != nil {
			return readErr
		}
	}
	return nil
}

func TestEncryptMediaRoundTrip(t *testing.T) {
	dir := t.TempDir()
	src := filepath.Join(dir, "clip.mkv")
	enc := filepath.Join(dir, "clip.mkv.cmdata")
	dec := filepath.Join(dir, "clip-out.mkv")
	plain := []byte("fake movie bytes 12345")
	if err := os.WriteFile(src, plain, 0644); err != nil {
		t.Fatal(err)
	}
	key, err := NewMediaLockKey()
	if err != nil {
		t.Fatal(err)
	}
	if err := EncryptMediaFile(src, enc, key); err != nil {
		t.Fatal(err)
	}
	st, _ := os.Stat(enc)
	if st.Size() <= int64(len(plain)) {
		t.Fatalf("encrypted size unexpected: %d", st.Size())
	}
	if err := decryptMediaForTest(enc, key, dec); err != nil {
		t.Fatal(err)
	}
	got, err := os.ReadFile(dec)
	if err != nil {
		t.Fatal(err)
	}
	if string(got) != string(plain) {
		t.Fatalf("roundtrip mismatch")
	}
	b64 := MediaLockKeyB64(key)
	if b64 != base64.StdEncoding.EncodeToString(key) {
		t.Fatalf("MediaLockKeyB64 mismatch: %q", b64)
	}
}

func TestEncryptMediaFileEmptyKey(t *testing.T) {
	dir := t.TempDir()
	src := filepath.Join(dir, "x.bin")
	if err := os.WriteFile(src, []byte("x"), 0644); err != nil {
		t.Fatal(err)
	}
	err := EncryptMediaFile(src, filepath.Join(dir, "out.bin"), nil)
	if err == nil || !strings.Contains(err.Error(), "empty") {
		t.Fatalf("expected empty key error, got %v", err)
	}
}

func TestEncryptMediaFileMissingSource(t *testing.T) {
	key, err := NewMediaLockKey()
	if err != nil {
		t.Fatal(err)
	}
	err = EncryptMediaFile(filepath.Join(t.TempDir(), "missing.bin"), filepath.Join(t.TempDir(), "out.bin"), key)
	if err == nil {
		t.Fatal("expected open error for missing source")
	}
}

func TestNewMediaLockKeyLength(t *testing.T) {
	key, err := NewMediaLockKey()
	if err != nil {
		t.Fatal(err)
	}
	if len(key) != 32 {
		t.Fatalf("expected 32-byte key, got %d", len(key))
	}
}

