package loadsim

import (
	"flag"
	"testing"
	"time"
)

func TestConfigFromFlagsParsesCapacityKnobs(t *testing.T) {
	fs := flag.NewFlagSet("load-sim", flag.ContinueOnError)
	cfg := RegisterFlags(fs)

	err := fs.Parse([]string{
		"-protocol", "jt808",
		"-addr", "115.29.187.205:808",
		"-connections", "10000",
		"-connect-rate", "800",
		"-send-interval", "5s",
		"-duration", "30m",
		"-template", "0200",
		"-jt808-phone-base", "138900000000",
		"-send=false",
	})
	if err != nil {
		t.Fatalf("parse flags: %v", err)
	}

	got, err := cfg.Build()
	if err != nil {
		t.Fatalf("build config: %v", err)
	}

	if got.Protocol != ProtocolJT808 {
		t.Fatalf("Protocol = %q, want %q", got.Protocol, ProtocolJT808)
	}
	if got.Addr != "115.29.187.205:808" {
		t.Fatalf("Addr = %q", got.Addr)
	}
	if got.Connections != 10000 {
		t.Fatalf("Connections = %d", got.Connections)
	}
	if got.ConnectRatePerSecond != 800 {
		t.Fatalf("ConnectRatePerSecond = %d", got.ConnectRatePerSecond)
	}
	if got.SendInterval != 5*time.Second {
		t.Fatalf("SendInterval = %s", got.SendInterval)
	}
	if got.Duration != 30*time.Minute {
		t.Fatalf("Duration = %s", got.Duration)
	}
	if got.Template != "0200" {
		t.Fatalf("Template = %q", got.Template)
	}
	if got.SendFrames {
		t.Fatal("SendFrames = true, want false")
	}
	if got.JT808PhoneBase != 138900000000 {
		t.Fatalf("JT808PhoneBase = %d, want 138900000000", got.JT808PhoneBase)
	}
	if !got.DrainResponses {
		t.Fatal("DrainResponses = false, want true by default")
	}
}

func TestConfigFromFlagsRejectsUnsafeValues(t *testing.T) {
	for name, args := range map[string][]string{
		"missing addr":      {"-protocol", "jt808", "-connections", "1"},
		"bad protocol":      {"-protocol", "x", "-addr", "127.0.0.1:808", "-connections", "1"},
		"zero connections":  {"-protocol", "jt808", "-addr", "127.0.0.1:808", "-connections", "0"},
		"zero connect rate": {"-protocol", "jt808", "-addr", "127.0.0.1:808", "-connections", "1", "-connect-rate", "0"},
		"zero interval":     {"-protocol", "jt808", "-addr", "127.0.0.1:808", "-connections", "1", "-send-interval", "0s"},
		"phone overflow":    {"-protocol", "jt808", "-addr", "127.0.0.1:808", "-connections", "2", "-jt808-phone-base", "999999999999"},
	} {
		t.Run(name, func(t *testing.T) {
			fs := flag.NewFlagSet("load-sim", flag.ContinueOnError)
			cfg := RegisterFlags(fs)
			if err := fs.Parse(args); err != nil {
				t.Fatalf("parse flags: %v", err)
			}
			if _, err := cfg.Build(); err == nil {
				t.Fatalf("Build() error = nil, want validation error")
			}
		})
	}
}
