package mq

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

type captureClient struct{ payload []byte }

func (c *captureClient) Publish(_ context.Context, _ string, payload []byte, _ byte, _ bool) error {
	c.payload = append([]byte(nil), payload...)
	return nil
}
func (*captureClient) Subscribe(context.Context, string, byte, Handler) error { return nil }
func (*captureClient) Unsubscribe(context.Context, ...string) error           { return nil }
func (*captureClient) Connected() bool                                        { return true }
func (*captureClient) Close() error                                           { return nil }

func TestDisabledMQTTIsSafeAndUnavailable(t *testing.T) {
	client, err := NewMQTT(Config{})
	if err != nil {
		t.Fatal(err)
	}
	if client.Connected() {
		t.Fatal("disabled client reported connected")
	}
	if err = client.Publish(context.Background(), "events/test", []byte("test"), AtLeastOnce, false); !errors.Is(err, ErrUnavailable) {
		t.Fatalf("publish error = %v", err)
	}
	if err = client.Close(); err != nil {
		t.Fatal(err)
	}
	if err = client.Close(); err != nil {
		t.Fatalf("second close: %v", err)
	}
}

func TestEnabledMQTTRequiresBroker(t *testing.T) {
	if _, err := NewMQTT(Config{Enabled: true}); err == nil {
		t.Fatal("enabled MQTT without a broker should fail")
	}
}

func TestPublishAndDecodeJSON(t *testing.T) {
	client := &captureClient{}
	if err := PublishJSON(context.Background(), client, "orders/paid", map[string]int{"id": 7}, AtLeastOnce, false); err != nil {
		t.Fatal(err)
	}
	var value map[string]int
	if err := (Message{Payload: client.payload}).DecodeJSON(&value); err != nil {
		t.Fatal(err)
	}
	if value["id"] != 7 {
		t.Fatalf("decoded value = %#v", value)
	}
}
