package config

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

func TestLoadDefaultsEnableOutboxRetention(t *testing.T) {
	cfg, err := Load("")
	if err != nil {
		t.Fatalf("Load(empty) failed: %v", err)
	}
	retention := cfg.LuckyGiftWorker.Retention
	if !retention.Enabled {
		t.Fatal("retention should be enabled by default")
	}
	if retention.MaxAge != 7*24*time.Hour {
		t.Fatalf("retention.MaxAge = %s, want 168h", retention.MaxAge)
	}
	if retention.ScanInterval != 5*time.Minute {
		t.Fatalf("retention.ScanInterval = %s, want 5m", retention.ScanInterval)
	}
	if retention.BatchSize != 500 {
		t.Fatalf("retention.BatchSize = %d, want 500", retention.BatchSize)
	}
}

func TestLoadRunnableConfigsPublishLuckyGiftOwnerOutbox(t *testing.T) {
	for _, path := range []string{"../../configs/config.yaml", "../../configs/config.docker.yaml", "../../configs/config.tencent.example.yaml"} {
		cfg, err := Load(path)
		if err != nil {
			t.Fatalf("Load(%s) failed: %v", path, err)
		}
		if !cfg.RocketMQ.Enabled || !cfg.RocketMQ.LuckyGiftOutbox.Enabled {
			t.Fatalf("%s must enable lucky owner outbox: %+v", path, cfg.RocketMQ)
		}
		if cfg.RocketMQ.LuckyGiftOutbox.Topic != "hyapp_lucky_gift_outbox" || cfg.RocketMQ.LuckyGiftOutbox.ProducerGroup == "" {
			t.Fatalf("%s has incomplete lucky owner routing: %+v", path, cfg.RocketMQ.LuckyGiftOutbox)
		}
	}
}

func TestLoadLocalUsesComposeRocketMQHostPort(t *testing.T) {
	cfg, err := Load("../../configs/config.yaml")
	if err != nil {
		t.Fatalf("load local config: %v", err)
	}
	if len(cfg.RocketMQ.NameServers) != 1 || cfg.RocketMQ.NameServers[0] != "127.0.0.1:19876" {
		t.Fatalf("local config must use compose host-mapped nameserver port: %+v", cfg.RocketMQ.NameServers)
	}
}

func TestLoadRejectsEnabledRocketMQWithoutEndpoint(t *testing.T) {
	path := filepath.Join(t.TempDir(), "config.yaml")
	content := `
rocketmq:
  enabled: true
  lucky_gift_outbox:
    enabled: true
`
	if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
		t.Fatalf("write config: %v", err)
	}
	if _, err := Load(path); err == nil || !strings.Contains(err.Error(), "name_servers") {
		t.Fatalf("Load should reject missing RocketMQ endpoint, got err=%v", err)
	}
}

func TestLoadRejectsRetentionMaxAgeBelowSafetyFloor(t *testing.T) {
	path := filepath.Join(t.TempDir(), "config.yaml")
	content := `
lucky_gift_worker:
  retention:
    enabled: true
    max_age: 30s
`
	if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
		t.Fatalf("write config: %v", err)
	}
	if _, err := Load(path); err == nil || !strings.Contains(err.Error(), "safety floor") {
		t.Fatalf("Load should reject max_age below 24h, got err=%v", err)
	}
}
