<?php

namespace NoahVet\Reef\RabbitMQ\Producer;

use NoahVet\Reef\RabbitMQ\InternalQueueTrait;
use NoahVet\Reef\RabbitMQ\Notification\ReefNotificationInterface;
use NoahVet\Reef\RabbitMQ\Task\InternalTaskInterface;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AbstractConnection;
use PhpAmqpLib\Message\AMQPMessage;
use Symfony\Component\Serializer\SerializerInterface;

class ReefMQProducer implements ReefMQProducerInterface
{
    use InternalQueueTrait;

    protected AMQPChannel $channel;

    public function __construct(
        AbstractConnection $connection,
        protected readonly string $reefAppName,
        protected readonly SerializerInterface $serializer,
    ) {
        $this->channel = $connection->channel();
        $this->declareQueue($this->channel, $this->reefAppName);
    }

    #[\Override]
    public function publishNotification(ReefNotificationInterface $notification): void
    {
        $message = new AMQPMessage(
            $this->serializer->serialize($notification, 'json'),
            [
                'content_encoding' => 'application/json',
                'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
            ],
        );

        $this->channel->basic_publish(
            $message,
            'reef-notify',
            $this->reefAppName,
        );
    }

    #[\Override]
    public function publishTask(InternalTaskInterface $task): void
    {
        $message = new AMQPMessage(
            $this->serializer->serialize($task, 'json'),
            [
                'content_encoding' => 'application/json',
                'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
            ],
        );

        $this->channel->basic_publish(
            $message,
            '',
            $this->reefAppName,
        );
    }
}
