<?php

namespace KupShop\MessengerBundle\Handler;

use KupShop\KupShopBundle\Util\Logging\SentryLogger;
use KupShop\KupShopBundle\Util\Mail\EmailSender;
use KupShop\MessengerBundle\Message\EmailMessage;

class FinalEmailHandler
{
    use \DatabaseCommunication;

    public function __construct(
        protected SentryLogger $sentryLogger,
        protected EmailSender $emailSender,
    ) {
    }

    protected bool $isLast = false;

    public function __invoke(EmailMessage $message)
    {
        $result = true;
        $resultMessage = 'OK';

        try {
            $service = $message->getEmailService();
            $email = $message->getMessage();

            // generate attachments
            $email['attachments'] = array_merge($email['attachments'] ?? [], $service->getAttachments($email['template'] ?? []));

            // finally send email
            $msg = $this->emailSender->createMessage($email['from'], $email['to'], $email['subject'], $email['body'], 'text/html', $email['attachments'], $email['cc'] ?? null, $email['bcc'] ?? null, [], strtolower($email['type']), $email['id'] ?? 'not yet');

            if ($this->emailSender->sendMessage($msg, !$this->isLast)) {
                // update orders_history notified status only if it is not admin email (admin email should not be visible to users on FE)
                if (!empty($email['id_history']) && empty($email['isAdminEmail'])) {
                    $this->updateSQL('orders_history', ['notified' => 1], ['id' => $email['id_history']]);
                }
            } else {
                $result = false;
            }
        } catch (\Throwable $e) {
            $this->sentryLogger->captureException($e);

            $result = false;
            $resultMessage = $e->getMessage();
        }

        // pokud je to posledni pokus odeslani a selze to, tak nastavime status notified na 5 (Selhalo)
        if ($this->isLast) {
            try {
                if (!$result) {
                    if (!empty($email['id_history'])) {
                        $this->updateSQL('orders_history', ['notified' => 5], ['id' => $email['id_history']]);
                    }
                }
            } catch (\Exception $e) {
                $this->sentryLogger->captureException($e);
            }
        }

        return [
            'status' => $result,
            'message' => $resultMessage,
        ];
    }

    public function setIsLast($isLast)
    {
        $this->isLast = $isLast;
    }

    /**
     * @required
     */
    public function setSentryLogger(SentryLogger $sentryLogger)
    {
        $this->sentryLogger = $sentryLogger;
    }
}
