<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Mailer\Command;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Messenger\Messaging\CommandHandlerInterface;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils\Mailer;
use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Cart\Repository\CartRepository;
use CpCreation\VitiCore\Contact\Repository\ContactRepository;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;

#[AsMessageHandler]
final readonly class OrderMailCommandHandler implements CommandHandlerInterface
{
    public function __construct(
        private CartRepository $cartRepository,
        private ContactRepository $contactRepository,
        private Mailer $mailer,
    ) {
    }

    public function __invoke(OrderMailCommand $command): void
    {
        $cart = $this->cartRepository->find($command->cartId);
        if (!$cart instanceof Cart) {
            throw new UnrecoverableMessageHandlingException(\sprintf('Commande introuvable pour l\'email asynchrone: %s', $command->cartId));
        }

        $contact = $this->contactRepository->findOne();
        if (null === $contact) {
            throw new UnrecoverableMessageHandlingException('Aucun contact boutique n\'est configuré pour envoyer les emails de commande.');
        }

        match ($command->type) {
            OrderMailCommand::TYPE_OFFLINE_ORDER => $this->mailer->sendOfflineOrder($contact, $cart),
            OrderMailCommand::TYPE_PAID_ORDER => $this->mailer->sendPaidOrder($contact, $cart),
            OrderMailCommand::TYPE_ORDER_CUSTOMER => $this->mailer->sendOrderCustomer($contact, $cart),
            OrderMailCommand::TYPE_ORDER_RESEND_CUSTOMER => $this->mailer->sendResendOrderCustomer($contact, $cart),
            OrderMailCommand::TYPE_DELIVERY => $this->mailer->sendDelivery($contact, $cart),
            OrderMailCommand::TYPE_CREDIT_CUSTOMER => $this->mailer->sendCreditCustomer($contact, $cart),
            default => throw new UnrecoverableMessageHandlingException(\sprintf('Type d\'email de commande inconnu: %s', $command->type)),
        };
    }
}
