package handlers

import (
	"encoding/json"
	"strings"
	"testing"

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

func TestDiagnosticPrivacyAITurnKeepsMetricsWithoutConversationText(t *testing.T) {
	db := workflowTestDB(t)
	if err := db.AutoMigrate(&models.AITurn{}, &models.ClosingRecord{}); err != nil {
		t.Fatal(err)
	}
	logAITurn(1, "628001", "private-question", "private-reply", "fixture", 1, false, false, "", 8, services.RetrievalTrace{RetrievalMode: "agentic", RetrievalQuery: "private-query", KnowledgeIDs: "3", ToolCalls: 2})
	var row models.AITurn
	db.First(&row)
	if row.UserMessage != "" || row.AIReply != "" || row.RetrievalQuery != "" || row.ResponseChars != 13 || row.KnowledgeIDs != "3" || row.Sender != "628001" {
		t.Fatalf("content minimized incorrectly: chars=%d", row.ResponseChars)
	}
	// An existing pre-metadata row with zero response_chars must still count.
	db.Create(&models.AITurn{AgentID: 1, Sender: "628002", AIReply: "legacy reply"})
	logAITurn(1, testAITurnSender, "simulation question", "simulation reply", "fixture", 0, false, false, "", 3, services.RetrievalTrace{})
	w := workflowRequest(t, AgentAIMetrics, nil, gin.Params{{Key: "id", Value: "1"}})
	var body map[string]any
	if json.Unmarshal(w.Body.Bytes(), &body) != nil || w.Code != 200 || body["ai_replies"] != float64(2) {
		t.Fatalf("metrics dropped metadata/legacy reply or counted simulation: code=%d body=%s", w.Code, w.Body.String())
	}
}

func TestDiagnosticPrivacyAITurnErrorsRemainClassified(t *testing.T) {
	db := workflowTestDB(t)
	if err := db.AutoMigrate(&models.AITurn{}); err != nil {
		t.Fatal(err)
	}
	for _, errText := range []string{"ai: provider request failed secret-private", "shipping: rejected secret-private"} {
		logAITurn(1, "628001", "", "", "fixture", 0, true, false, errText, 5, services.RetrievalTrace{})
	}
	var rows []models.AITurn
	db.Order("id").Find(&rows)
	if len(rows) != 2 || rows[0].Error != "ai:execution_failed" || rows[1].Error != "shipping:execution_failed" {
		t.Fatal("raw diagnostics remained or ai/shipping failure class lost")
	}
}

func TestDiagnosticPrivacyHandlerLogExportDoesNotPersistAPIResponse(t *testing.T) {
	workflowTestDB(t)
	simulationTestStore(t)
	t.Setenv("AI_SIMULATION_LOG_CONTENT", "false")
	id, session := services.NewSimulationID(), services.NewSimulationID()
	w := workflowRequest(t, func(c *gin.Context) {
		r, turn, sid, ok := startSimulationLog(c, models.Agent{ID: 1}, id, session, "private-question", []models.ChatHistory{{Message: "private-history"}})
		if !ok {
			return
		}
		respondSimulation(c, r, turn, sid, 200, gin.H{"reply": "private-response", "response_chars": 16, "response_validated": true})
	}, nil, nil)
	if !strings.Contains(w.Body.String(), "private-response") {
		t.Fatal("privacy filter changed actual simulator answer")
	}
	w = workflowRequest(t, func(c *gin.Context) { c.Request.URL.RawQuery = "detail=1"; GetSimulationLog(c) }, nil, gin.Params{{Key: "id", Value: "1"}, {Key: "turnID", Value: id}})
	if w.Code != 200 || strings.Contains(w.Body.String(), "private-") || !strings.Contains(w.Body.String(), `"content_mode":"metadata"`) {
		t.Fatalf("export privacy/disclosure mismatch: code=%d", w.Code)
	}
}
