<?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\AdminBundle\Components\Offer;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;
use Ferienpass\CoreBundle\Message\ReorderParticipantList;
use Ferienpass\CoreBundle\Repository\OfferRepositoryInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Uid\Uuid;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent(route: 'live_component_admin')]
class ReorderModal extends AbstractController
{
    use ComponentToolsTrait;
    use DefaultActionTrait;

    #[LiveProp]
    public ?OfferInterface $offer = null;

    #[LiveProp(writable: true)]
    public ?int $maxParticipants = null;

    #[LiveProp(writable: true)]
    public bool $reorder = true;

    #[LiveProp(writable: true)]
    public bool $notify = true;

    #[LiveProp(writable: true)]
    public bool $commit = true;

    public bool $success = false;
    public ?string $notificationUuid = null;

    public function __construct(private readonly OfferRepositoryInterface $offerRepository, private readonly MessageBusInterface $commandBus, private readonly EntityManagerInterface $entityManager)
    {
    }

    public function mount(?OfferInterface $offer = null): void
    {
        $this->offer = $offer;

        if ($this->offer) {
            $this->maxParticipants = ($this->offer->getMaxParticipants() ?: 0) + 1;
        }
    }

    #[LiveAction]
    public function submit(): void
    {
        if (null === $this->offer) {
            return;
        }

        if (null !== $this->maxParticipants) {
            $this->offer->setMaxParticipants($this->maxParticipants);
            $this->entityManager->flush();
        }

        if ($this->reorder) {
            $this->notificationUuid = (string) Uuid::v7();
            $this->commandBus->dispatch(new ReorderParticipantList((string) $this->offer->getUuid(), $this->notify, $this->commit, forceReorder: true, group: $this->notificationUuid));
        }

        $this->success = true;
    }
}
