package main

import (
	"math/rand"
	"os"
	"path/filepath"
	"testing"
	"time"

	"git.tornberg.me/go-cart-actor/pkg/cart"
)

// TestAppendFileInfoRandomProjectFile picks a random existing .go source file in the
// repository (from a small curated list to keep the test hermetic) and verifies
// that appendFileInfo populates Size, Modified and System without mutating the
// identity fields (ID, CartId). The randomness is only to satisfy the requirement
// of using "a random project file"; the test behavior is deterministic enough for
// CI because all chosen files are expected to exist.
func TestAppendFileInfoRandomProjectFile(t *testing.T) {
	candidates := []string{
		filepath.FromSlash("../../pkg/cart/cart_id.go"),
		filepath.FromSlash("../../pkg/actor/grain.go"),
		filepath.FromSlash("../../cmd/cart/main.go"),
	}
	// Pick one at random.
	rand.Seed(time.Now().UnixNano())
	path := candidates[rand.Intn(len(candidates))]

	info, err := os.Stat(path)
	if err != nil {
		t.Fatalf("stat failed for %s: %v", path, err)
	}

	// Pre-populate a CartFileInfo with identity fields.
	origID := "test-id"
	origCartId := cart.CartId(12345)
	cf := &CartFileInfo{ID: origID, CartId: origCartId}

	// Call function under test.
	got := appendFileInfo(info, cf)

	if got != cf {
		t.Fatalf("appendFileInfo should return the same pointer instance")
	}

	if cf.ID != origID {
		t.Fatalf("ID mutated: expected %q got %q", origID, cf.ID)
	}
	if cf.CartId != origCartId {
		t.Fatalf("CartId mutated: expected %v got %v", origCartId, cf.CartId)
	}

	if cf.Size != info.Size() {
		t.Fatalf("Size mismatch: expected %d got %d", info.Size(), cf.Size)
	}

	mod := info.ModTime()
	// Allow small clock skew / coarse timestamp truncation.
	if cf.Modified.Before(mod.Add(-2*time.Second)) || cf.Modified.After(mod.Add(2*time.Second)) {
		t.Fatalf("Modified not within expected range: want ~%v got %v", mod, cf.Modified)
	}

}

// TestAppendFileInfoTempFile creates a temporary file to ensure Size and Modified
// are updated for a freshly written file with known content length.
func TestAppendFileInfoTempFile(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "temp.events.log")
	content := []byte("hello world\nanother line\n")
	if err := os.WriteFile(path, content, 0644); err != nil {
		t.Fatalf("write temp file failed: %v", err)
	}

	info, err := os.Stat(path)
	if err != nil {
		t.Fatalf("stat temp file failed: %v", err)
	}

	cf := &CartFileInfo{ID: "temp", CartId: cart.CartId(0)}
	appendFileInfo(info, cf)

	if cf.Size != int64(len(content)) {
		t.Fatalf("expected Size %d got %d", len(content), cf.Size)
	}
	if cf.Modified.IsZero() {
		t.Fatalf("Modified should be set")
	}
}
