package apps

import (
	"archive/zip"
	"bytes"
	"os"
	"path/filepath"
	"testing"
	"time"
)

// writeTestBundle writes a <dir>/.zddc.zip containing the given members.
// Shared by bundle + handler precedence tests.
func writeTestBundle(t *testing.T, dir string, members map[string]string) string {
	t.Helper()
	var buf bytes.Buffer
	zw := zip.NewWriter(&buf)
	for name, body := range members {
		w, err := zw.Create(name)
		if err != nil {
			t.Fatalf("zip create %s: %v", name, err)
		}
		if _, err := w.Write([]byte(body)); err != nil {
			t.Fatalf("zip write %s: %v", name, err)
		}
	}
	if err := zw.Close(); err != nil {
		t.Fatalf("zip close: %v", err)
	}
	p := filepath.Join(dir, BundleName)
	if err := os.WriteFile(p, buf.Bytes(), 0o644); err != nil {
		t.Fatalf("write bundle: %v", err)
	}
	return p
}

func TestBundle_Member_Hit(t *testing.T) {
	root := t.TempDir()
	writeTestBundle(t, root, map[string]string{"browse.html": "BUNDLE browse"})
	b := NewBundle(root, nil)
	got, ok := b.Member("browse.html")
	if !ok || string(got) != "BUNDLE browse" {
		t.Fatalf("Member = (%q,%v), want (BUNDLE browse,true)", got, ok)
	}
	// Case-insensitive lookup (matches URL folding).
	if _, ok := b.Member("BROWSE.HTML"); !ok {
		t.Errorf("case-insensitive member lookup failed")
	}
}

func TestBundle_Member_Absent(t *testing.T) {
	root := t.TempDir()
	writeTestBundle(t, root, map[string]string{"browse.html": "x"})
	b := NewBundle(root, nil)
	if _, ok := b.Member("archive.html"); ok {
		t.Errorf("absent member reported present")
	}
}

func TestBundle_NoFile(t *testing.T) {
	b := NewBundle(t.TempDir(), nil)
	if _, ok := b.Member("browse.html"); ok {
		t.Errorf("no bundle file but member reported present")
	}
	// nil bundle is safe.
	var nb *Bundle
	if _, ok := nb.Member("browse.html"); ok {
		t.Errorf("nil bundle reported a member")
	}
}

func TestBundle_HotReload(t *testing.T) {
	root := t.TempDir()
	p := writeTestBundle(t, root, map[string]string{"browse.html": "v1"})
	b := NewBundle(root, nil)
	if got, _ := b.Member("browse.html"); string(got) != "v1" {
		t.Fatalf("first read = %q, want v1", got)
	}
	// Rewrite with new bytes + a bumped mtime so the stat-based cache reparses.
	writeTestBundle(t, root, map[string]string{"browse.html": "v2"})
	_ = os.Chtimes(p, time.Now().Add(2*time.Second), time.Now().Add(2*time.Second))
	if got, _ := b.Member("browse.html"); string(got) != "v2" {
		t.Errorf("after reload = %q, want v2", got)
	}
}

func TestBundle_CorruptZip(t *testing.T) {
	root := t.TempDir()
	if err := os.WriteFile(filepath.Join(root, BundleName), []byte("not a zip"), 0o644); err != nil {
		t.Fatal(err)
	}
	b := NewBundle(root, nil)
	if _, ok := b.Member("browse.html"); ok {
		t.Errorf("corrupt zip should yield no members")
	}
}
