package config

import "testing"

func TestOutboxWorkerAppCodesNormalizeForStagedReplay(t *testing.T) {
	cfg := Default()
	cfg.OutboxWorker.AppCodes = []string{" LALU ", "fami", "HUWAA", "fami"}
	if err := cfg.Normalize(); err != nil {
		t.Fatalf("normalize staged outbox config: %v", err)
	}
	if len(cfg.OutboxWorker.AppCodes) != 3 || cfg.OutboxWorker.AppCodes[0] != "lalu" || cfg.OutboxWorker.AppCodes[1] != "fami" || cfg.OutboxWorker.AppCodes[2] != "huwaa" {
		t.Fatalf("normalized outbox app_codes = %v", cfg.OutboxWorker.AppCodes)
	}
}

func TestLocalOutboxWorkerEmptyAppCodesUsesDiscovery(t *testing.T) {
	cfg, err := Load("../../configs/config.yaml")
	if err != nil {
		t.Fatalf("load local config: %v", err)
	}
	if len(cfg.OutboxWorker.AppCodes) != 0 {
		t.Fatalf("local empty app_codes must retain automatic discovery: %v", cfg.OutboxWorker.AppCodes)
	}
}

func TestLoadConfigsKeepActivityServiceAddr(t *testing.T) {
	tests := []struct {
		name string
		path string
		want string
	}{
		{name: "local", path: "../../configs/config.yaml", want: "127.0.0.1:13006"},
		{name: "docker", path: "../../configs/config.docker.yaml", want: "activity-service:13006"},
		{name: "tencent", path: "../../configs/config.tencent.example.yaml", want: "10.2.1.16:13006"},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			cfg, err := Load(tt.path)
			if err != nil {
				t.Fatalf("Load %s config failed: %v", tt.name, err)
			}
			if cfg.ActivityServiceAddr != tt.want {
				t.Fatalf("activity service addr mismatch: got %q want %q", cfg.ActivityServiceAddr, tt.want)
			}
		})
	}
}

func TestLoadConfigsEnableRoomRPSIM(t *testing.T) {
	tests := []struct {
		name string
		path string
	}{
		{name: "local", path: "../../configs/config.yaml"},
		{name: "docker", path: "../../configs/config.docker.yaml"},
		{name: "tencent", path: "../../configs/config.tencent.example.yaml"},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			cfg, err := Load(tt.path)
			if err != nil {
				t.Fatalf("Load %s config failed: %v", tt.name, err)
			}
			if !cfg.TencentIM.Enabled {
				t.Fatalf("room-rps tencent_im must be enabled in %s config", tt.name)
			}
			if cfg.TencentIM.SDKAppID <= 0 || cfg.TencentIM.SecretKey == "" || cfg.TencentIM.AdminIdentifier == "" {
				t.Fatalf("room-rps tencent_im config is incomplete: sdk_app_id_set=%t secret_key_set=%t admin_identifier_set=%t", cfg.TencentIM.SDKAppID > 0, cfg.TencentIM.SecretKey != "", cfg.TencentIM.AdminIdentifier != "")
			}
			if cfg.TencentIM.Endpoint != "adminapisgp.im.qcloud.com" {
				t.Fatalf("room-rps tencent_im endpoint mismatch: %q", cfg.TencentIM.Endpoint)
			}
		})
	}
}

func TestNormalizeRejectsEnabledIncompleteTencentIM(t *testing.T) {
	cfg := Default()
	cfg.TencentIM.Enabled = true
	cfg.TencentIM.SDKAppID = 0
	cfg.TencentIM.SecretKey = ""
	cfg.TencentIM.AdminIdentifier = ""

	if err := cfg.Normalize(); err == nil {
		t.Fatal("Normalize should reject enabled incomplete tencent_im config")
	}
}
