package handlers_test

import (
	"net/http/httptest"

	"os"
	"testing"
	"time"

	"erp_system/internal/database"
	"erp_system/internal/handlers"

	"github.com/gorilla/sessions"
)

func TestJournalEntries_List(t *testing.T) {
	// Setup temporary DB
	dbFile := "test_ledger.db"
	db, err := database.Initialize(dbFile)
	if err != nil {
		t.Fatalf("Failed to initialize DB: %v", err)
	}
	defer func() {
		db.Close()
		os.Remove(dbFile)
	}()

	// Setup Handler
	store := sessions.NewCookieStore([]byte("secret"))
	h := &handlers.Handler{
		DB:    db,
		Store: store,
	}

	// Insert a dummy entry so the loop runs
	db.Exec("INSERT INTO journal_entries (description) VALUES ('Test')")

	// Create a timeout channel to detect freeze
	done := make(chan bool)
	go func() {
		req := httptest.NewRequest("GET", "/ledger/journal", nil)
		w := httptest.NewRecorder()

		// Execute Handler
		h.JournalEntries(w, req)

		done <- true
	}()

	select {
	case <-done:
		t.Log("Handler completed successfully")
	case <-time.After(2 * time.Second):
		t.Fatal("Handler timed out - DEADLOCK DETECTED")
	}
}
