<?php


namespace Shop\Application\Shopping\SendProviderOrders;


use Diamond\Application\Notification\Exceptions\NotificationException;
use Diamond\Application\Notification\NotificationService;
use Shop\Application\Shopping\PrepareProviderOrderDataForReport\PrepareProviderOrderDataForReportCommand;
use Shop\Application\Shopping\PrepareProviderOrderDataForReport\Result;
use Shop\Domain\ProviderOrder\ProviderOrderCollection;
use Shop\Repositories\ProviderOrder\ProviderOrderRepository;

class SendProviderOrdersHandler
{
    protected $providerOrderRepository;
    protected $notificationService;

    public function __construct(ProviderOrderRepository $providerOrderRepository,
                                NotificationService $notificationService)
    {
        $this->providerOrderRepository = $providerOrderRepository;
        $this->notificationService = $notificationService;
    }

    /**
     * @param SendProviderOrdersCommand $command
     * @throws \Repo\Concrete\Exceptions\Collection
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function handle(SendProviderOrdersCommand $command): void
    {
        $errors = [];

        $ids = $command->getIds();

        $successOrders = new ProviderOrderCollection();
        /**
         * @var Order $order
         */
        foreach ($ids as $id) {

            if (!$order = $this->providerOrderRepository->findById($id)) {
                $errors[] = $id;
            }

            $result = new Result();
            $this->commandBus->handle(new PrepareProviderOrderDataForReportCommand($order, $result));
            $data = $result->getData();

            try {
                $email = $order->getContractor()->getEmail();
                $this->notificationService->sendToEmailByReport('provider_order_notify', $email, $data);

                $successOrders->push($order);

            } catch (NotificationException $ex) {
                $errors[] = $order->getId();
            }
        }

        if (count($errors)) {
            throw new SendProviderOrdersException($successOrders, 'send providers orders errors: ' . implode(',', $errors));
        }

        $command->getResultOrders()->setOrders($successOrders);
    }

}