<?php

declare(strict_types=1);

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;

    private AMQPChannel $channel;

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

    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,
        );
    }

    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,
        );
    }
}
