package services

import (
	"context"
	"strings"
	"testing"

	"wa-assistant/backend/models"
)

func TestDirectServiceAnswersRequireResolutionAndAllowSupportedLimits(t *testing.T) {
	db := agenticTestDB(t)
	k := models.Knowledge{AgentID: 1, Question: "Apakah bisa shared hosting?", Answer: "Belum bisa untuk shared hosting. Aplikasi ini memerlukan VPS.", Active: true, ReviewStatus: "published"}
	if err := db.Create(&k).Error; err != nil {
		t.Fatal(err)
	}
	state := &agentTurnState{reviewAnswer: approveTestAnswer, knowledge: []models.Knowledge{k}, userMessage: k.Question, policy: responsePolicyForLength(selectAIResponsePolicy(k.Question, "", "", 1), "short", k.Question)}
	for _, tc := range []struct{ answer, issue string }{
		{"Setahu saya aplikasi ini memerlukan VPS.", "indirect_answer"},
		{"Belum bisa untuk shared hosting, Kak. Aplikasi ini memerlukan VPS.", ""},
	} {
		out := state.checkAnswer(context.Background(), 1, answerCheckInput{Answer: tc.answer, SourceIDs: []uint{k.ID}, Kind: "answer"})
		if out.Issue != tc.issue {
			t.Fatalf("%q: got=%s want=%s", tc.answer, out.Issue, tc.issue)
		}
		// Both standard and agentic modes apply the same direct-answer guard.
		if issue := responseFormatIssue(tc.answer, state.policy); issue != tc.issue {
			t.Fatal("standard mode uses a different service style", issue)
		}
	}
	// Unrelated installation evidence cannot justify a negative compatibility
	// claim. Exercise the review rejection/approval lifecycle with a verdict.
	other := models.Knowledge{AgentID: 1, Question: "Instalasi aplikasi", Answer: "Tersedia panduan instalasi lokal. Tim teknis membantu setup di server.", Active: true, ReviewStatus: "published"}
	if err := db.Create(&other).Error; err != nil {
		t.Fatal(err)
	}
	state.knowledge = []models.Knowledge{other}
	state.reviewAnswer = func(_ context.Context, _, _, evidence string) (answerEvidenceReview, error) {
		if !strings.Contains(evidence, other.Answer) || strings.Contains(evidence, k.Answer) {
			t.Fatal("review did not receive only the selected source")
		}
		return answerEvidenceReview{Supported: false, UnsupportedClaims: []string{"Kompatibilitas shared hosting tidak disebut"}}, nil
	}
	if out := state.checkAnswer(context.Background(), 1, answerCheckInput{Answer: "Aplikasi belum bisa untuk shared hosting, gunakan instalasi lokal.", SourceIDs: []uint{other.ID}, Kind: "answer"}); out.Approved || out.Issue != "unsupported_claims" || state.approved != nil {
		t.Fatal("unsupported negative survives review", out.Issue)
	}
}
