<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Tests\NotificationHandler;

use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Entity\Edition;
use Ferienpass\CoreBundle\Entity\EditionTask;
use Ferienpass\CoreBundle\Entity\Host;
use Ferienpass\CoreBundle\Entity\Offer\Base;
use Ferienpass\CoreBundle\Entity\Participant\BaseParticipant;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Message\ApplicationsClosed as ApplicationsClosedEvent;
use Ferienpass\CoreBundle\Message\HostCreated as HostCreatedEvent;
use Ferienpass\CoreBundle\Message\OfferCompleteNotify as OfferCompleteEvent;
use Ferienpass\CoreBundle\Message\OfferRelaunched as OfferRelaunchedEvent;
use Ferienpass\CoreBundle\Message\PaymentReceiptCreated as PaymentReceiptCreatedEvent;
use Ferienpass\CoreBundle\Message\RemindAttendance as RemindAttendanceEvent;
use Ferienpass\CoreBundle\Notification\ApplicationsClosedNotification;
use Ferienpass\CoreBundle\NotificationHandler\ApplicationsClosed;
use Ferienpass\CoreBundle\NotificationHandler\HostCreated;
use Ferienpass\CoreBundle\NotificationHandler\OfferComplete;
use Ferienpass\CoreBundle\NotificationHandler\OfferRelaunched;
use Ferienpass\CoreBundle\NotificationHandler\PaymentReceiptCreated;
use Ferienpass\CoreBundle\NotificationHandler\PhoneFormatter;
use Ferienpass\CoreBundle\NotificationHandler\RemindAttendance;
use Ferienpass\CoreBundle\Notifier\Notifier;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Ferienpass\CoreBundle\Repository\HostRepository;
use Ferienpass\CoreBundle\Repository\OfferRepositoryInterface;
use Ferienpass\CoreBundle\Repository\PaymentRepository;
use Ferienpass\CoreBundle\Repository\UserRepository;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Uid\Uuid;

final class MoreNotificationsTest extends TestCase
{
    // ---- RemindAttendance ----

    public function testRemindAttendanceDoesNothingWhenAttendanceNotFound(): void
    {
        $attendanceUuid = (string) Uuid::v7();
        $attendances = $this->createMock(AttendanceRepository::class);
        $attendances->method('findBy')->with(['uuid' => [$attendanceUuid]])->willReturn([]);

        $notifier = $this->createMock(Notifier::class);
        $notifier->expects(self::never())->method('send');

        $handler = new RemindAttendance($notifier, $attendances, new PhoneFormatter());
        $handler(new RemindAttendanceEvent($attendanceUuid), Uuid::v7());
    }

    public function testRemindAttendanceDoesNothingWhenRecipientHasNoEmail(): void
    {
        $offer = new Base();
        $participant = new BaseParticipant();
        $attendance = new Attendance($offer, $participant);
        $attendanceUuid = (string) Uuid::v7();

        $attendances = $this->createMock(AttendanceRepository::class);
        $attendances->method('findBy')->with(['uuid' => [$attendanceUuid]])->willReturn([$attendance]);

        $notifier = $this->createMock(Notifier::class);
        // No resolvable recipient, so we never even build the notification.
        $notifier->expects(self::never())->method('remindAttendance');
        $notifier->expects(self::never())->method('send');

        $handler = new RemindAttendance($notifier, $attendances, new PhoneFormatter());
        $handler(new RemindAttendanceEvent($attendanceUuid), Uuid::v7());
    }

    public function testRemindAttendanceDoesNothingWhenNotifierReturnsNull(): void
    {
        $offer = new Base();
        $participant = new BaseParticipant();
        $participant->setEmail('parent@example.com');
        $attendance = new Attendance($offer, $participant);
        $attendanceUuid = (string) Uuid::v7();

        $attendances = $this->createMock(AttendanceRepository::class);
        $attendances->method('findBy')->with(['uuid' => [$attendanceUuid]])->willReturn([$attendance]);

        $notifier = $this->createMock(Notifier::class);
        $notifier->method('remindAttendance')->willReturn(null);
        $notifier->expects(self::never())->method('send');

        $handler = new RemindAttendance($notifier, $attendances, new PhoneFormatter());
        $handler(new RemindAttendanceEvent($attendanceUuid), Uuid::v7());
    }

    // ---- OfferRelaunched ----

    public function testOfferRelaunchedDoesNothingWhenNotifierReturnsNull(): void
    {
        $offer = new Base();
        $participant = new BaseParticipant();
        $attendance = new Attendance($offer, $participant);
        $attendanceUuid = (string) Uuid::v7();

        $attendances = $this->createMock(AttendanceRepository::class);
        $attendances->method('findOneBy')->with(['uuid' => $attendanceUuid])->willReturn($attendance);

        $notifier = $this->createMock(Notifier::class);
        $notifier->method('offerRelaunched')->willReturn(null);
        $notifier->expects(self::never())->method('send');

        $handler = new OfferRelaunched($notifier, $attendances, new PhoneFormatter());
        $handler(new OfferRelaunchedEvent($attendanceUuid, (string) Uuid::v7()), Uuid::v7());
    }

    // ---- HostCreated ----

    public function testHostCreatedDoesNothingWhenUserNotFound(): void
    {
        $users = $this->createMock(UserRepository::class);
        $users->method('find')->willReturn(null);

        $notifier = $this->createMock(Notifier::class);
        $notifier->expects(self::never())->method('send');

        $handler = new HostCreated(
            $notifier,
            $this->createMock(HostRepository::class),
            $users,
            $this->createMock(UrlGeneratorInterface::class)
        );
        $handler(new HostCreatedEvent((string) Uuid::v7(), (string) Uuid::v7()), Uuid::v7());
    }

    public function testHostCreatedDoesNothingWhenHostNotFound(): void
    {
        $user = new User();
        $users = $this->createMock(UserRepository::class);
        $users->method('find')->willReturn($user);

        $hosts = $this->createMock(HostRepository::class);
        $hosts->method('find')->willReturn(null);

        $notifier = $this->createMock(Notifier::class);
        $notifier->expects(self::never())->method('send');

        $handler = new HostCreated(
            $notifier,
            $hosts,
            $users,
            $this->createMock(UrlGeneratorInterface::class)
        );
        $handler(new HostCreatedEvent((string) Uuid::v7(), (string) Uuid::v7()), Uuid::v7());
    }

    public function testHostCreatedDoesNothingWhenNotifierReturnsNull(): void
    {
        $user = new User();
        $host = new Host();

        $users = $this->createMock(UserRepository::class);
        $users->method('find')->willReturn($user);

        $hosts = $this->createMock(HostRepository::class);
        $hosts->method('find')->willReturn($host);

        $notifier = $this->createMock(Notifier::class);
        $notifier->method('hostCreated')->willReturn(null);
        $notifier->expects(self::never())->method('send');

        $handler = new HostCreated(
            $notifier,
            $hosts,
            $users,
            $this->createMock(UrlGeneratorInterface::class)
        );
        $handler(new HostCreatedEvent((string) Uuid::v7(), (string) Uuid::v7()), Uuid::v7());
    }

    // ---- OfferComplete ----

    public function testOfferCompleteDoesNothingWhenOfferNotFound(): void
    {
        $offerId = (string) Uuid::v7();
        $offers = $this->createMock(OfferRepositoryInterface::class);
        $offers->method('findOneBy')->with(['uuid' => $offerId])->willReturn(null);

        $notifier = $this->createMock(Notifier::class);
        $notifier->expects(self::never())->method('send');

        $handler = new OfferComplete($notifier, $offers, $this->createMock(UrlGeneratorInterface::class));
        $handler(new OfferCompleteEvent($offerId), Uuid::v7());
    }

    public function testOfferCompleteDoesNothingWhenNotifierReturnsNull(): void
    {
        $offer = new Base();
        $offerId = (string) Uuid::v7();

        $offers = $this->createMock(OfferRepositoryInterface::class);
        $offers->method('findOneBy')->with(['uuid' => $offerId])->willReturn($offer);

        $notifier = $this->createMock(Notifier::class);
        $notifier->method('offerComplete')->willReturn(null);
        $notifier->expects(self::never())->method('send');

        $handler = new OfferComplete($notifier, $offers, $this->createMock(UrlGeneratorInterface::class));
        $handler(new OfferCompleteEvent($offerId), Uuid::v7());
    }

    // ---- PaymentReceiptCreated ----

    public function testPaymentReceiptCreatedDoesNothingWhenNotifyFalse(): void
    {
        $notifier = $this->createMock(Notifier::class);
        $notifier->expects(self::never())->method('send');

        $handler = new PaymentReceiptCreated($notifier, $this->createMock(PaymentRepository::class));
        $handler(new PaymentReceiptCreatedEvent(Uuid::v7()->toRfc4122(), false), Uuid::v7());
    }

    public function testPaymentReceiptCreatedDoesNothingWhenNotifierReturnsNull(): void
    {
        $payment = $this->createMock(\Ferienpass\CoreBundle\Entity\Payment::class);
        $paymentUuid = Uuid::v7()->toRfc4122();

        $payments = $this->createMock(PaymentRepository::class);
        $payments->method('findOneBy')->with(['uuid' => $paymentUuid])->willReturn($payment);

        $notifier = $this->createMock(Notifier::class);
        $notifier->method('paymentCreated')->willReturn(null);
        $notifier->expects(self::never())->method('send');

        $handler = new PaymentReceiptCreated($notifier, $payments);
        $handler(new PaymentReceiptCreatedEvent($paymentUuid, true), Uuid::v7());
    }

    // ---- ApplicationsClosed ----

    public function testApplicationsClosedDoesNothingWhenOfferNotFound(): void
    {
        $offerId = (string) Uuid::v7();
        $offers = $this->createMock(OfferRepositoryInterface::class);
        $offers->method('findOneBy')->with(['uuid' => $offerId])->willReturn(null);

        $notifier = $this->createMock(Notifier::class);
        $notifier->expects(self::never())->method('send');

        $handler = new ApplicationsClosed($notifier, $offers, $this->createStub(UrlGeneratorInterface::class));
        $handler(new ApplicationsClosedEvent($offerId), Uuid::v7());
    }

    public function testApplicationsClosedDoesNothingWhenNotifierReturnsNull(): void
    {
        $offer = new Base();
        $offerId = (string) Uuid::v7();

        $offers = $this->createMock(OfferRepositoryInterface::class);
        $offers->method('findOneBy')->with(['uuid' => $offerId])->willReturn($offer);

        $notifier = $this->createMock(Notifier::class);
        $notifier->method('applicationsClosed')->willReturn(null);
        $notifier->expects(self::never())->method('send');

        $handler = new ApplicationsClosed($notifier, $offers, $this->createStub(UrlGeneratorInterface::class));
        $handler(new ApplicationsClosedEvent($offerId), Uuid::v7());
    }

    /**
     * The mail links straight into the participant list, so it waits for the
     * edition's "publish_lists" window rather than announcing a 403.
     */
    public function testApplicationsClosedDoesNothingWhileTheListIsWithheld(): void
    {
        $offerId = (string) Uuid::v7();
        $offer = new Base();
        $offer->setEdition($this->editionWithheldUntil(new \DateTimeImmutable('+2 days')));
        $offer->addHost($this->hostWithUser('host@example.org'));

        $offers = $this->createMock(OfferRepositoryInterface::class);
        $offers->method('findOneBy')->with(['uuid' => $offerId])->willReturn($offer);

        $notifier = $this->createMock(Notifier::class);
        $notifier->method('applicationsClosed')->willReturn(new ApplicationsClosedNotification());
        $notifier->expects(self::never())->method('send');

        $handler = new ApplicationsClosed($notifier, $offers, $this->createStub(UrlGeneratorInterface::class));
        $handler(new ApplicationsClosedEvent($offerId), Uuid::v7());
    }

    /**
     * The handler runs from a cron, i.e. without a logged-in user. It used to gate
     * on `is_granted('participants.view')`, which denies unconditionally in that
     * context, so the mail never went out at all.
     */
    public function testApplicationsClosedMailsTheHostsUsersWithoutALoggedInUser(): void
    {
        $offerId = (string) Uuid::v7();
        $offer = new Base();
        $offer->setEdition(new Edition());
        $offer->addHost($this->hostWithUser('host@example.org'));

        $offers = $this->createMock(OfferRepositoryInterface::class);
        $offers->method('findOneBy')->with(['uuid' => $offerId])->willReturn($offer);

        $notifier = $this->createMock(Notifier::class);
        $notifier->method('applicationsClosed')->willReturn(new ApplicationsClosedNotification());
        $notifier->expects(self::once())->method('send')->with(
            self::isInstanceOf(ApplicationsClosedNotification::class),
            self::callback(static fn (Recipient $r) => 'host@example.org' === $r->getEmail()),
        );

        $handler = new ApplicationsClosed($notifier, $offers, $this->createStub(UrlGeneratorInterface::class));
        $handler(new ApplicationsClosedEvent($offerId), Uuid::v7());
    }

    private function editionWithheldUntil(\DateTimeImmutable $begin): Edition
    {
        $edition = new Edition();

        $task = new EditionTask($edition);
        $task->setType('publish_lists');
        $task->setPeriodBegin($begin);
        $task->setPeriodEnd($begin->modify('+7 days'));

        $edition->addTask($task);

        return $edition;
    }

    private function hostWithUser(string $email): Host
    {
        $user = new User();
        $user->setEmail($email);

        $host = new Host();
        $host->addMember($user);

        return $host;
    }
}
