package cql

import (
	"testing"
	"time"

	"github.com/everything-on-mysql/cassandra-on-mysql/pkg/metrics"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func TestAppendBatchLogFields(t *testing.T) {
	tracker := metrics.NewRequestMetrics(0x0D, 9, time.Unix(0, 0))
	tracker.SetBatchInfo("UNLOGGED", 5, 2, 2, 5)
	tracker.SetClientPayload(map[string]string{"thread-index": "3"})

	fields := appendBatchLogFields(nil, tracker)
	got := zapFieldsToMap(fields)

	if got["batch_type"] != "UNLOGGED" {
		t.Fatalf("expected batch_type UNLOGGED, got %#v", got["batch_type"])
	}
	if got["batch_input_statement_count"] != int64(5) {
		t.Fatalf("expected batch_input_statement_count 5, got %#v", got["batch_input_statement_count"])
	}
	if got["batch_execute_plan_count"] != int64(2) {
		t.Fatalf("expected batch_execute_plan_count 2, got %#v", got["batch_execute_plan_count"])
	}
	if got["batch_merge_applied"] != true {
		t.Fatalf("expected batch_merge_applied true, got %#v", got["batch_merge_applied"])
	}
	payload, ok := got["client_payload"].(map[string]string)
	if !ok || len(payload) != 1 || payload["thread-index"] != "3" {
		t.Fatalf("expected client_payload with thread-index=3, got %#v", got["client_payload"])
	}
}

func TestAppendBatchLogFieldsSkipsEmptyBatchInfo(t *testing.T) {
	tracker := metrics.NewRequestMetrics(0x0D, 9, time.Unix(0, 0))

	fields := appendBatchLogFields([]zap.Field{zap.String("keep", "value")}, tracker)
	got := zapFieldsToMap(fields)

	if len(got) != 1 {
		t.Fatalf("expected only existing field to remain, got %#v", got)
	}
	if got["keep"] != "value" {
		t.Fatalf("expected keep=value, got %#v", got["keep"])
	}
}

func zapFieldsToMap(fields []zap.Field) map[string]interface{} {
	enc := zapcore.NewMapObjectEncoder()
	for _, field := range fields {
		field.AddTo(enc)
	}
	return enc.Fields
}
