package acceptance

import (
	"encoding/json"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

func TestSplitSQLDropsCommentsAndKeepsStatements(t *testing.T) {
	script := `
-- comment before first statement
SELECT 1;

-- comment before second statement
SELECT '{{RUN_ID}}';
`

	statements := splitSQL(script)
	if len(statements) != 2 {
		t.Fatalf("len(statements) = %d, want 2: %#v", len(statements), statements)
	}
	if statements[0] != "SELECT 1" {
		t.Fatalf("first statement = %q", statements[0])
	}
	if statements[1] != "SELECT '{{RUN_ID}}'" {
		t.Fatalf("second statement = %q", statements[1])
	}
}

func TestSanitizeBodyTruncatesLongBodies(t *testing.T) {
	raw := []byte(strings.Repeat("a", 600))
	got := sanitizeBody(raw)
	if len(got) <= 512 {
		t.Fatalf("sanitized body length = %d, want truncation marker", len(got))
	}
	if !strings.Contains(got, "<truncated>") {
		t.Fatalf("sanitized body missing truncation marker: %q", got)
	}
}

func TestWriteReportCreatesJSONArtifact(t *testing.T) {
	dir := t.TempDir()
	reportPath := filepath.Join(dir, "report.json")

	original := acceptanceReporter
	acceptanceReporter = &Reporter{started: time.Now()}
	t.Cleanup(func() {
		acceptanceReporter = original
	})

	recordCase(t, "public", "GET", "/v1/public/user/info", "200 envelope")
	if err := writeReport(Config{
		RunID:      "qa_test",
		StagingURL: "https://tapi.hifast.biz",
		ReportPath: reportPath,
	}); err != nil {
		t.Fatalf("write report: %v", err)
	}

	raw, err := os.ReadFile(reportPath)
	if err != nil {
		t.Fatalf("read report: %v", err)
	}
	var report Report
	if err := json.Unmarshal(raw, &report); err != nil {
		t.Fatalf("decode report: %v", err)
	}
	if report.RunID != "qa_test" {
		t.Fatalf("run id = %q", report.RunID)
	}
	if len(report.Cases) != 1 {
		t.Fatalf("cases len = %d, want 1", len(report.Cases))
	}
}
