<?php

/**
 * 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.
 */

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\CalendarBundle\Controller;

use Chill\CalendarBundle\Messenger\Message\MSGraphChangeNotificationMessage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Annotation\Route;

class RemoteCalendarMSGraphSyncController
{
    public function __construct(private readonly MessageBusInterface $messageBus) {}

    #[Route(path: '/public/incoming-hook/calendar/msgraph/events/{userId}', name: 'chill_calendar_remote_msgraph_incoming_webhook_events', methods: ['POST'])]
    public function webhookCalendarReceiver(int $userId, Request $request): Response
    {
        if ($request->query->has('validationToken')) {
            return new Response($request->query->get('validationToken'), Response::HTTP_OK, [
                'content-type' => 'text/plain',
            ]);
        }

        try {
            $body = json_decode($request->getContent(), true, 512, \JSON_THROW_ON_ERROR);
        } catch (\JsonException $e) {
            throw new BadRequestHttpException('could not decode json', $e);
        }

        $this->messageBus->dispatch(new MSGraphChangeNotificationMessage($body, $userId));

        return new Response('', Response::HTTP_ACCEPTED);
    }
}
