package services

import (
	"context"
	"os"
	"testing"
	"wa-assistant/backend/models"
)

func TestServiceExtractionRejectsInventedAndForeignFields(t *testing.T) {
	raw := `{"fields":{"name":{"value":"Rina","evidence":"nama Rina"},"schedule":{"value":"2026-09-08","evidence":"besok jam 10"},"_edit_submission_id":{"value":"10","evidence":"10"},"quantity":{"value":"3","evidence":"3 orang"}},"question":"Harga berapa?"}`
	got, err := parseServiceExtraction(raw, "Mau booking besok jam 10, nama Rina.", []ServiceField{{Key: "name"}, {Key: "schedule"}, {Key: "quantity"}})
	if err != nil || len(got.Fields) != 1 || got.Fields["name"].Value != "Rina" || got.Question != "" {
		t.Fatalf("unsafe proposal accepted: %+v %v", got, err)
	}
}

func TestServiceExtractionSupportsSeveralFactsAndSideQuestion(t *testing.T) {
	raw := `{"fields":{"name":{"value":"Rina","evidence":"nama Rina"},"schedule":{"value":"besok jam 10","evidence":"besok jam 10"}},"question":"Biayanya berapa?"}`
	got, err := parseServiceExtraction(raw, "Nama saya sebelumnya Ani, sekarang nama Rina, jadwal besok jam 10. Biayanya berapa?", []ServiceField{{Key: "name"}, {Key: "schedule"}})
	if err != nil || len(got.Fields) != 2 || got.Question != "Biayanya berapa?" {
		t.Fatalf("%+v %v", got, err)
	}
}

func TestLiveServiceExtraction(t *testing.T) {
	if os.Getenv("CHATLOOP_RUN_LIVE_AI") != "1" {
		t.Skip("opt-in OpenRouter test")
	}
	p := liveAIPresetForTest(t)
	db := agenticTestDB(t)
	if err := db.AutoMigrate(&models.AppSetting{}); err != nil {
		t.Fatal(err)
	}
	fields := []ServiceField{{Key: "name", Label: "Nama pelanggan", Type: "text", Required: true}, {Key: "schedule", Label: "Jadwal konsultasi", Type: "text", Required: true}, {Key: "quantity", Label: "Jumlah orang", Type: "number", Required: true}}
	t.Logf("Two synthetic service extraction scenarios through %s; no WhatsApp or customer writes", p.Model)
	first, err := ExtractServiceFields(context.Background(), 1, "Booking konsultasi", fields, map[string]string{}, "", "Mau booking besok jam 10, nama Rina.")
	if err != nil {
		t.Fatal(err)
	}
	if first.Fields["name"].Value != "Rina" || first.Fields["schedule"].Value != "besok jam 10" || len(first.Fields) != 2 {
		t.Fatalf("unexpected fixture extraction: %+v", first)
	}
	second, err := ExtractServiceFields(context.Background(), 1, "Booking konsultasi", fields, map[string]string{"name": "Rina", "schedule": "besok jam 10"}, "quantity", "Untuk 3 orang. Kalau ubah jadwal boleh?")
	if err != nil {
		t.Fatal(err)
	}
	if second.Fields["quantity"].Value != "3" || second.Question == "" || second.Handoff {
		t.Fatalf("unexpected fixture extraction: %+v", second)
	}
}
