<?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\RemoteCalendar\Connector\MSGraph\OnBehalfOfUserTokenStorage;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use TheNetworg\OAuth2\Client\Provider\Azure;
use TheNetworg\OAuth2\Client\Token\AccessToken;

class RemoteCalendarConnectAzureController
{
    public function __construct(private readonly ClientRegistry $clientRegistry, private readonly OnBehalfOfUserTokenStorage $MSGraphTokenStorage) {}

    #[Route(path: '/{_locale}/connect/azure', name: 'chill_calendar_remote_connect_azure')]
    public function connectAzure(Request $request): Response
    {
        $request->getSession()->set('azure_return_path', $request->query->get('returnPath', '/'));

        return $this->clientRegistry
            ->getClient('azure') // key used in config/packages/knpu_oauth2_client.yaml
            ->redirect(['https://graph.microsoft.com/.default', 'offline_access'], []);
    }

    #[Route(path: '/connect/azure/check', name: 'chill_calendar_remote_connect_azure_check')]
    public function connectAzureCheck(Request $request): Response
    {
        /** @var Azure $client */
        $client = $this->clientRegistry->getClient('azure');

        try {
            /** @var AccessToken $token */
            $token = $client->getAccessToken([]);

            $this->MSGraphTokenStorage->setToken($token);
        } catch (IdentityProviderException $e) {
            throw $e;
        }

        return new RedirectResponse($request->getSession()->remove('azure_return_path', '/'));
    }
}
