package handlers

import (
	"encoding/json"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/gin-gonic/gin"
	"wa-assistant/backend/models"
)

// Opt-in loopback fixture serves the actual built UI and real PDF/review routes.
// No member database, credentials or WhatsApp session are attached.
func TestPDFBrowserFixture(t *testing.T) {
	ready := os.Getenv("CHATLOOP_PDF_BROWSER_FILE")
	if ready == "" {
		t.Skip("browser harness only")
	}
	db := workflowTestDB(t)
	db.AutoMigrate(&models.AppSetting{})
	t.Setenv("OPENROUTER_API_KEY", "")
	t.Setenv("DEEPSEEK_API_KEY", "")
	db.Model(&models.Agent{}).Where("id = ?", 1).Updates(map[string]any{"name": "CS Contoh", "system_prompt": "Asisten virtual toko contoh.", "tone": "ramah", "agentic_enabled": true})
	r := gin.New()
	r.Use(gin.Recovery())
	api := r.Group("/api", func(c *gin.Context) { c.Set("tenant_id", uint(1)); c.Set("user_id", uint(7)); c.Set("role", "admin") })
	api.GET("/agents", func(c *gin.Context) { var rows []models.Agent; db.Find(&rows); c.JSON(200, gin.H{"data": rows}) })
	api.PUT("/agents/:id", UpdateAgent)
	api.GET("/agents/:id/knowledge", ListKnowledge)
	api.POST("/agents/:id/knowledge/pdf", ImportKnowledgePDF)
	api.POST("/agents/:id/knowledge/:kid/review", ReviewKnowledge)
	api.GET("/agents/:id/ai-readiness", GetAIReadiness)
	dist, _ := filepath.Abs("../../frontend/dist")
	r.Static("/assets", filepath.Join(dist, "assets"))
	r.NoRoute(func(c *gin.Context) {
		if strings.HasPrefix(c.Request.URL.Path, "/api/") {
			c.JSON(200, gin.H{"data": []any{}, "status": "disconnected", "used_chars": 0, "max_chars": 0, "max_pages": 0})
			return
		}
		c.File(filepath.Join(dist, "index.html"))
	})
	server := httptest.NewServer(r)
	defer server.Close()
	raw, _ := json.Marshal(map[string]string{"url": server.URL})
	if os.WriteFile(ready, raw, 0600) != nil {
		t.Fatal("cannot write browser address")
	}
	defer os.Remove(ready)
	timer := time.NewTimer(4 * time.Minute)
	defer timer.Stop()
	tick := time.NewTicker(250 * time.Millisecond)
	defer tick.Stop()
	for {
		select {
		case <-timer.C:
			t.Fatal("browser fixture expired")
		case <-tick.C:
			if _, err := os.Stat(ready + ".done"); err == nil {
				os.Remove(ready + ".done")
				return
			}
		}
	}
}
