<?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\ZimbraBundle\Exception\ZimbraCalendarIdNotDeserializedException;

/**
 * Serializes and deserializes Zimbra calendar event IDs.
 *
 * This class handles the conversion between Zimbra's individual ID components
 * and a single serialized string format, allowing for consistent storage and retrieval
 * of Zimbra calendar event identifiers.
 */
final readonly class ZimbraIdSerializer
{
    /**
     * Serializes individual Zimbra calendar ID components into a single string.
     *
     * @param string $calItemId                The calendar item ID from Zimbra
     * @param string $calInvId                 The calendar invitation ID from Zimbra
     * @param string $inviteComponentCommonUid The common UID for the invite component
     *
     * @return string The serialized ID in format "calItemId|calInvId|inviteComponentCommonUid|v0"
     */
    public function serializeId(string $calItemId, string $calInvId, string $inviteComponentCommonUid): string
    {
        return sprintf(
            '%s|%s|%s|v0',
            $calItemId,
            $calInvId,
            $inviteComponentCommonUid,
        );
    }

    /**
     * Deserializes a Zimbra calendar ID string into its component parts.
     *
     * @param string $remoteId The serialized ID, as stored in the remoteId's Calendar or CalendarRange
     *
     * @return array{calItemId: string, calInvId: string, inviteComponentCommonUid: string} Associative array containing the ID components
     *
     * @throws ZimbraCalendarIdNotDeserializedException If the remote ID format is invalid or incompatible
     */
    public function deSerializeId(string $remoteId): array
    {
        if (!str_ends_with($remoteId, 'v0')) {
            throw new ZimbraCalendarIdNotDeserializedException();
        }

        $exploded = explode('|', $remoteId);

        return [
            'calItemId' => $exploded[0],
            'calInvId' => $exploded[1],
            'inviteComponentCommonUid' => $exploded[2],
        ];
    }
}
