package publisher

import (
	"context"
	"encoding/json"

	"github.com/charmingruby/homunc/apps/fraud/pkg/messaging/rabbitmq"
)

const (
	checkoutsExchange                    = "checkouts.events"
	baseCheckoutsAvailabilityStatusTopic = "checkouts."
)

type RabbitMQPublisher struct {
	queue *rabbitmq.Client
}

func New(queue *rabbitmq.Client) *RabbitMQPublisher {
	return &RabbitMQPublisher{
		queue: queue,
	}
}

type DispatchCheckoutAvailabilityStatusMessage struct {
	UserID    string `json:"userId"`
	SessionID string `json:"sessionId"`
	Country   string `json:"country"`
}

func (p *RabbitMQPublisher) DispatchCheckoutAvailabilityStatus(
	ctx context.Context,
	status AvailabilityStatus,
	msg DispatchCheckoutAvailabilityStatusMessage,
) error {
	jsonMsg, err := json.Marshal(msg)
	if err != nil {
		return err
	}

	topic := baseCheckoutsAvailabilityStatusTopic + status

	_, err = p.queue.Publish(
		ctx,
		rabbitmq.PublishInput{
			Exchange:   checkoutsExchange,
			RoutingKey: topic,
			Message:    jsonMsg,
		},
	)

	return err
}
