package mq

import (
	"context"
	"errors"
	"testing"
)

func TestDisabledRabbitMQIsSafeAndUnavailable(t *testing.T) {
	client, err := NewRabbitMQ(RabbitMQConfig{})
	if err != nil {
		t.Fatal(err)
	}
	if client.Connected() {
		t.Fatal("disabled rabbitmq reported connected")
	}
	if err = client.Publish(context.Background(), "orders.paid", []byte("test"), AtLeastOnce, false); !errors.Is(err, ErrUnavailable) {
		t.Fatalf("publish error = %v", err)
	}
	if err = client.Close(); err != nil {
		t.Fatal(err)
	}
}

func TestEnabledRabbitMQRequiresTopology(t *testing.T) {
	if _, err := NewRabbitMQ(RabbitMQConfig{Enabled: true}); err == nil {
		t.Fatal("enabled rabbitmq without host and topology should fail")
	}
}

func TestRabbitRoutingKeyMatches(t *testing.T) {
	tests := []struct {
		pattern string
		key     string
		want    bool
	}{
		{pattern: "orders.*.paid", key: "orders.cn.paid", want: true},
		{pattern: "orders.#", key: "orders.cn.created", want: true},
		{pattern: "#.paid", key: "orders.cn.paid", want: true},
		{pattern: "orders.*", key: "orders.cn.paid", want: false},
		{pattern: "orders.created", key: "orders.paid", want: false},
	}
	for _, test := range tests {
		if got := rabbitRoutingKeyMatches("topic", test.pattern, test.key); got != test.want {
			t.Fatalf("match(%q, %q) = %v, want %v", test.pattern, test.key, got, test.want)
		}
	}
}
