<?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\Commerce\Catalog\Outbox;

use CpCreation\VitiCore\Commerce\Catalog\CatalogContract;
use CpCreation\VitiCore\Commerce\Catalog\Configuration\CatalogWebhookEndpointResolver;
use CpCreation\VitiCore\Commerce\Catalog\Model\CatalogChange;

final readonly class CatalogWebhookRequestFactory
{
    public function __construct(
        private CatalogWebhookEndpointResolver $webhookEndpointResolver,
        private CatalogWebhookSigner $signer,
    ) {}

    public function create(CatalogChange $change, \DateTimeImmutable $sentAt): CatalogWebhookRequest
    {
        $eventId = $change->getEventId()->toString();
        $instanceId = $change->getInstanceId()->toString();
        $timestamp = $sentAt->format('U');
        $body = json_encode([
            'schema_version' => CatalogContract::SCHEMA_VERSION,
            'cursor' => $change->getCursor(),
            'event_id' => $eventId,
            'instance_id' => $instanceId,
            'type' => $change->getType()->value,
            'resource_type' => $change->getResourceType()->value,
            'resource_id' => $change->getResourceId(),
            'occurred_at' => $change->getOccurredAt()
                ->setTimezone(new \DateTimeZone('UTC'))
                ->format(\DATE_ATOM),
        ], \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES);

        return new CatalogWebhookRequest($body, [
            'Content-Type' => 'application/json',
            'User-Agent' => CatalogContract::USER_AGENT,
            'Idempotency-Key' => $eventId,
            'X-Serenity-Timestamp' => $timestamp,
            'X-Serenity-Instance' => $instanceId,
            'X-Serenity-Event-Id' => $eventId,
            'X-Serenity-Signature' => $this->signer->sign(
                $this->webhookEndpointResolver->secret(),
                $timestamp,
                $body,
            ),
        ]);
    }
}
