package actor

import (
	"log"

	"github.com/matst80/slask-finder/pkg/messaging"
	amqp "github.com/rabbitmq/amqp091-go"
)

type LogListener interface {
	AppendMutations(id uint64, msg ...ApplyResult)
}

type AmqpListener struct {
	conn        *amqp.Connection
	transformer func(id uint64, msg []ApplyResult) (any, error)
}

func NewAmqpListener(conn *amqp.Connection, transformer func(id uint64, msg []ApplyResult) (any, error)) *AmqpListener {
	return &AmqpListener{
		conn:        conn,
		transformer: transformer,
	}
}

func (l *AmqpListener) DefineTopics() {
	ch, err := l.conn.Channel()
	if err != nil {
		log.Fatalf("Failed to open a channel: %v", err)
	}
	defer ch.Close()
	if err := messaging.DefineTopic(ch, "cart", "mutation"); err != nil {
		log.Fatalf("Failed to declare topic mutation: %v", err)
	}
}

func (l *AmqpListener) AppendMutations(id uint64, msg ...ApplyResult) {
	data, err := l.transformer(id, msg)
	if err != nil {
		log.Printf("Failed to transform mutation event: %v", err)
		return
	}
	err = messaging.SendChange(l.conn, "cart", "mutation", data)
	if err != nil {
		log.Printf("Failed to send mutation event: %v", err)
	}
}
