package main

import (
	"context"
	"strings"
	"testing"

	"github.com/DATA-DOG/go-sqlmock"

	"lingniu-vehicle-ingest/go/vehicle-gateway/internal/loadsim"
)

func TestFormatStatsIncludesCapacityCounters(t *testing.T) {
	out := formatStats(loadsim.Stats{
		ConnectionsOpened: 10,
		ConnectionsFailed: 2,
		FramesWritten:     300,
		WriteErrors:       1,
		ResponseBytes:     2048,
		ReadErrors:        0,
	})

	for _, want := range []string{
		"connections_opened=10",
		"connections_failed=2",
		"frames_written=300",
		"write_errors=1",
		"response_bytes=2048",
		"read_errors=0",
	} {
		if !strings.Contains(out, want) {
			t.Fatalf("formatStats() = %q, missing %q", out, want)
		}
	}
}

func TestCleanupJT808RegistrationsUsesBoundedLoopbackDelete(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()
	mock.ExpectExec(`DELETE FROM jt808_registration`).
		WithArgs("139000000000", "139000000999").
		WillReturnResult(sqlmock.NewResult(0, 1000))

	deleted, err := cleanupJT808RegistrationsWithDB(context.Background(), db, loadsim.Config{
		Protocol:       loadsim.ProtocolJT808,
		Connections:    1000,
		JT808PhoneBase: loadsim.DefaultJT808PhoneBase,
	})
	if err != nil {
		t.Fatalf("cleanupJT808RegistrationsWithDB() error = %v", err)
	}
	if deleted != 1000 {
		t.Fatalf("deleted = %d, want 1000", deleted)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatal(err)
	}
}
