<?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\Tests\RemoteCalendar\Connector\MSGraph;

use Chill\CalendarBundle\Entity\Calendar;
use Chill\CalendarBundle\Entity\CalendarRange;
use Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph\RemoteToLocalSync\CalendarRangeSyncer;
use Chill\MainBundle\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Psr\Log\NullLogger;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;

/**
 * @internal
 *
 * @coversNothing
 */
final class CalendarRangeSyncerTest extends TestCase
{
    use ProphecyTrait;

    private const NOTIF_DELETE = <<<'JSON'
        {
            "value": [
                {
                    "subscriptionId": "077e8d19-68b3-4d8e-9b1e-8b4ba6733799",
                    "subscriptionExpirationDateTime": "2022-06-09T06:22:02-07:00",
                    "changeType": "deleted",
                    "resource": "Users/4feb0ae3-7ffb-48dd-891e-c86b2cdeefd4/Events/AAMkADM1MTdlMGIzLTZhZWUtNDQ0ZC05Y2M4LWViMjhmOWJlMDhhMQBGAAAAAAA5e3965gkBSLcU1p00sMSyBwAHduaxajFfTpv0kchk_m1FAAAAAAENAAAHduaxajFfTpv0kchk_m1FAAAl1BupAAA=",
                    "resourceData": {
                        "@odata.type": "#Microsoft.Graph.Event",
                        "@odata.id": "Users/4feb0ae3-7ffb-48dd-891e-c86b2cdeefd4/Events/AAMkADM1MTdlMGIzLTZhZWUtNDQ0ZC05Y2M4LWViMjhmOWJlMDhhMQBGAAAAAAA5e3965gkBSLcU1p00sMSyBwAHduaxajFfTpv0kchk_m1FAAAAAAENAAAHduaxajFfTpv0kchk_m1FAAAl1BupAAA=",
                        "@odata.etag": "W/\"CQAAAA==\"",
                        "id": "AAMkADM1MTdlMGIzLTZhZWUtNDQ0ZC05Y2M4LWViMjhmOWJlMDhhMQBGAAAAAAA5e3965gkBSLcU1p00sMSyBwAHduaxajFfTpv0kchk_m1FAAAAAAENAAAHduaxajFfTpv0kchk_m1FAAAl1BupAAA="
                    },
                    "clientState": "uds18apRCByqWIodFCHKeM0kJqhfr+qXL/rJWYn7xmtdQ4t03W2OHEOdGJ0Ceo52NAzOYVDpbfRM3TdrZDUiE09OxZkPX/vkpdcnipoiVnPPMFBQn05p8KhklOM=",
                    "tenantId": "421bf216-3f48-47bd-a7cf-8b1995cb24bd"
                }
            ]
        }
        JSON;

    private const NOTIF_UPDATE = <<<'JSON'
        {
            "value": [
                {
                    "subscriptionId": "739703eb-80c4-4c03-b15a-ca370f19624b",
                    "subscriptionExpirationDateTime": "2022-06-09T02:40:28-07:00",
                    "changeType": "updated",
                    "resource": "Users/4feb0ae3-7ffb-48dd-891e-c86b2cdeefd4/Events/AAMkADM1MTdlMGIzLTZhZWUtNDQ0ZC05Y2M4LWViMjhmOWJlMDhhMQBGAAAAAAA5e3965gkBSLcU1p00sMSyBwAHduaxajFfTpv0kchk_m1FAAAAAAENAAAHduaxajFfTpv0kchk_m1FAAAl1BupAAA=",
                    "resourceData": {
                        "@odata.type": "#Microsoft.Graph.Event",
                        "@odata.id": "Users/4feb0ae3-7ffb-48dd-891e-c86b2cdeefd4/Events/AAMkADM1MTdlMGIzLTZhZWUtNDQ0ZC05Y2M4LWViMjhmOWJlMDhhMQBGAAAAAAA5e3965gkBSLcU1p00sMSyBwAHduaxajFfTpv0kchk_m1FAAAAAAENAAAHduaxajFfTpv0kchk_m1FAAAl1BupAAA=",
                        "@odata.etag": "W/\"DwAAABYAAAAHduaxajFfTpv0kchk+m1FAAAlyzAU\"",
                        "id": "AAMkADM1MTdlMGIzLTZhZWUtNDQ0ZC05Y2M4LWViMjhmOWJlMDhhMQBGAAAAAAA5e3965gkBSLcU1p00sMSyBwAHduaxajFfTpv0kchk_m1FAAAAAAENAAAHduaxajFfTpv0kchk_m1FAAAl1BupAAA="
                    },
                    "clientState": "2k05qlr3ds2KzvUP3Ps4A+642fYaI8ThxHGIGbNr2p0MnNkmzxLTNEMxpMc/UEuDkBHfID7OYWj4DQc94vlEkPBdsh9sGTTkHxIE68hqkKkDKhwvfvdj6lS6Dus=",
                    "tenantId": "421bf216-3f48-47bd-a7cf-8b1995cb24bd"
                }
            ]
        }
        JSON;

    private const REMOTE_CALENDAR_RANGE = <<<'JSON'
        {
            "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('4feb0ae3-7ffb-48dd-891e-c86b2cdeefd4')/events/$entity",
            "@odata.etag": "W/\"B3bmsWoxX06b9JHIZPptRQAAJcswFA==\"",
            "id": "AAMkADM1MTdlMGIzLTZhZWUtNDQ0ZC05Y2M4LWViMjhmOWJlMDhhMQBGAAAAAAA5e3965gkBSLcU1p00sMSyBwAHduaxajFfTpv0kchk_m1FAAAAAAENAAAHduaxajFfTpv0kchk_m1FAAAl1BupAAA=",
            "createdDateTime": "2022-06-08T15:22:24.0096697Z",
            "lastModifiedDateTime": "2022-06-09T09:27:09.9223729Z",
            "changeKey": "B3bmsWoxX06b9JHIZPptRQAAJcswFA==",
            "categories": [],
            "transactionId": "90c23105-a6b1-b594-1811-e4ffa612092a",
            "originalStartTimeZone": "Romance Standard Time",
            "originalEndTimeZone": "Romance Standard Time",
            "iCalUId": "040000008200E00074C5B7101A82E00800000000A971DA8D4B7BD801000000000000000010000000BE3F4A21C9008E4FB35A4DE1F80E0118",
            "reminderMinutesBeforeStart": 15,
            "isReminderOn": true,
            "hasAttachments": false,
            "subject": "test notif",
            "bodyPreview": "",
            "importance": "normal",
            "sensitivity": "normal",
            "isAllDay": false,
            "isCancelled": false,
            "isOrganizer": true,
            "responseRequested": true,
            "seriesMasterId": null,
            "showAs": "busy",
            "type": "singleInstance",
            "webLink": "https://outlook.office365.com/owa/?itemid=AAMkADM1MTdlMGIzLTZhZWUtNDQ0ZC05Y2M4LWViMjhmOWJlMDhhMQBGAAAAAAA5e3965gkBSLcU1p00sMSyBwAHduaxajFfTpv0kchk%2Bm1FAAAAAAENAAAHduaxajFfTpv0kchk%2Bm1FAAAl1BupAAA%3D&exvsurl=1&path=/calendar/item",
            "onlineMeetingUrl": null,
            "isOnlineMeeting": false,
            "onlineMeetingProvider": "unknown",
            "allowNewTimeProposals": true,
            "occurrenceId": null,
            "isDraft": false,
            "hideAttendees": false,
            "responseStatus": {
                "response": "organizer",
                "time": "0001-01-01T00:00:00Z"
            },
            "body": {
                "contentType": "html",
                "content": ""
            },
            "start": {
                "dateTime": "2022-06-10T13:30:00.0000000",
                "timeZone": "UTC"
            },
            "end": {
                "dateTime": "2022-06-10T15:30:00.0000000",
                "timeZone": "UTC"
            },
            "location": {
                "displayName": "",
                "locationType": "default",
                "uniqueIdType": "unknown",
                "address": {},
                "coordinates": {}
            },
            "locations": [],
            "recurrence": null,
            "attendees": [],
            "organizer": {
                "emailAddress": {
                    "name": "Diego Siciliani",
                    "address": "DiegoS@2zy74l.onmicrosoft.com"
                }
            },
            "onlineMeeting": null,
            "calendar@odata.associationLink": "https://graph.microsoft.com/v1.0/Users('4feb0ae3-7ffb-48dd-891e-c86b2cdeefd4')/calendar/$ref",
            "calendar@odata.navigationLink": "https://graph.microsoft.com/v1.0/Users('4feb0ae3-7ffb-48dd-891e-c86b2cdeefd4')/calendar"
        }
        JSON;

    public function testDeleteCalendarRangeWithAssociation(): void
    {
        $em = $this->prophesize(EntityManagerInterface::class);
        $em->remove(Argument::type(CalendarRange::class))->shouldNotBeCalled();

        $machineHttpClient = new MockHttpClient([
            new MockResponse(self::REMOTE_CALENDAR_RANGE, ['http_code' => 200]),
        ]);

        $calendarRangeSyncer = new CalendarRangeSyncer(
            $em->reveal(),
            new NullLogger(),
            $machineHttpClient
        );

        $calendarRange = new CalendarRange();
        $calendarRange
            ->setUser($user = new User());
        $calendar = new Calendar();
        $calendar->setCalendarRange($calendarRange);

        $notification = json_decode(self::NOTIF_DELETE, true);

        $calendarRangeSyncer->handleCalendarRangeSync(
            $calendarRange,
            $notification['value'][0],
            $user
        );
    }

    public function testDeleteCalendarRangeWithoutAssociation(): void
    {
        $em = $this->prophesize(EntityManagerInterface::class);
        $em->remove(Argument::type(CalendarRange::class))->shouldBeCalled();

        $machineHttpClient = new MockHttpClient([
            new MockResponse(self::REMOTE_CALENDAR_RANGE, ['http_code' => 200]),
        ]);

        $calendarRangeSyncer = new CalendarRangeSyncer(
            $em->reveal(),
            new NullLogger(),
            $machineHttpClient
        );

        $calendarRange = new CalendarRange();
        $calendarRange
            ->setUser($user = new User());
        $notification = json_decode(self::NOTIF_DELETE, true);

        $calendarRangeSyncer->handleCalendarRangeSync(
            $calendarRange,
            $notification['value'][0],
            $user
        );
        $this->assertTrue($calendarRange->preventEnqueueChanges);
    }

    public function testUpdateCalendarRange(): void
    {
        $em = $this->prophesize(EntityManagerInterface::class);
        $machineHttpClient = new MockHttpClient([
            new MockResponse(self::REMOTE_CALENDAR_RANGE, ['http_code' => 200]),
        ]);

        $calendarRangeSyncer = new CalendarRangeSyncer(
            $em->reveal(),
            new NullLogger(),
            $machineHttpClient
        );

        $calendarRange = new CalendarRange();
        $calendarRange
            ->setUser($user = new User())
            ->setStartDate(new \DateTimeImmutable('2020-01-01 15:00:00'))
            ->setEndDate(new \DateTimeImmutable('2020-01-01 15:30:00'))
            ->addRemoteAttributes([
                'lastModifiedDateTime' => 0,
                'changeKey' => 'abc',
            ]);
        $notification = json_decode(self::NOTIF_UPDATE, true);

        $calendarRangeSyncer->handleCalendarRangeSync(
            $calendarRange,
            $notification['value'][0],
            $user
        );

        $this->assertStringContainsString(
            '2022-06-10T15:30:00',
            $calendarRange->getStartDate()->format(\DateTimeImmutable::ATOM)
        );
        $this->assertStringContainsString(
            '2022-06-10T17:30:00',
            $calendarRange->getEndDate()->format(\DateTimeImmutable::ATOM)
        );
        $this->assertTrue($calendarRange->preventEnqueueChanges);
    }
}
