package main

import (
	"context"
	"fmt"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

type AmqpOrderHandler struct {
	Url        string
	Connection *amqp.Connection
	Channel    *amqp.Channel
}

func (h *AmqpOrderHandler) Connect() error {
	conn, err := amqp.Dial(h.Url)
	if err != nil {
		return fmt.Errorf("failed to connect to RabbitMQ: %w", err)
	}
	h.Connection = conn

	ch, err := conn.Channel()
	if err != nil {
		return fmt.Errorf("failed to open a channel: %w", err)
	}
	h.Channel = ch

	return nil
}

func (h *AmqpOrderHandler) Close() error {
	if h.Channel != nil {
		h.Channel.Close()
	}
	if h.Connection != nil {
		return h.Connection.Close()
	}
	return nil
}

func (h *AmqpOrderHandler) OrderCompleted(body []byte) error {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	err := h.Channel.PublishWithContext(ctx,
		"orders", // exchange
		"new",    // routing key
		false,    // mandatory
		false,    // immediate
		amqp.Publishing{
			ContentType: "application/json",
			Body:        body,
		})
	if err != nil {
		return fmt.Errorf("failed to publish a message: %w", err)
	}

	return nil
}
