<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\ZimbraBundle\Calendar\Connector\ZimbraConnector;

use Chill\MainBundle\Entity\User;
use Chill\ZimbraBundle\Exception\CalendarWithoutMainUserException;

/**
 * Represents an action to delete an existing Appointment in the Zimbra calendar.
 * The deletion is performed using the remoteId of the appointment.
 */
final readonly class DeleteEvent
{
    public function __construct(
        private SoapClientBuilder $soapClientBuilder,
        private ZimbraIdSerializer $zimbraIdSerializer,
    ) {}

    /**
     * Delete an existing Appointment in the Zimbra calendar, from his remoteId.
     *
     * @param User   $user     The user who owns the calendar
     * @param string $remoteId The remoteId of the appointment
     */
    public function __invoke(User $user, string $remoteId): void
    {
        $organizerEmail = $user->getEmail();

        if (null === $organizerEmail) {
            throw new CalendarWithoutMainUserException();
        }

        $api = $this->soapClientBuilder->getApiForAccount($organizerEmail);
        ['calItemId' => $calItemId, 'calInvId' => $calInvId, 'inviteComponentCommonUid' => $inviteComponentCommonUid]
            = $this->zimbraIdSerializer->deSerializeId($remoteId);

        $api->cancelAppointment(
            id: $calInvId,
            componentNum: 0,
        );
    }
}
