<?php

namespace App\Modules\HtlCampBooking\Application\UpdateAmount;

use App\Modules\HtlCampBooking\Application\Index\HtlCampBookingIndexer;
use App\Modules\HtlCampBooking\Domain\HtlCampBookingAmount;
use App\Modules\HtlCampBooking\Domain\IdHtlCampBooking;
use App\Modules\HtlCampSchedule\Application\Availability\AvailabilityHtlCampScheduleQuery;
use App\Modules\HtlCampSchedule\Application\ChangeUsage\ChangeUsageHtlCampScheduleQuery;
use App\Modules\HtlCampSchedule\Application\HtlCampScheduleResponse;
use App\Modules\HtlCampSchedule\Application\Index\IndexHtlCampScheduleQuery;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Domain\Bus\Query\QueryHandler;

final class UpdateAmountHtlCampBookingQueryHandler implements QueryHandler
{
    public function __construct(
        private HtlCampBookingAmountUpdater $updater,
        private HtlCampBookingIndexer $indexer,
        private QueryBus $queryBus
    ) {
    }

    public function __invoke(UpdateAmountHtlCampBookingQuery $query)
    {
        $index = $this->indexer->__invoke(new IdHtlCampBooking($query->id()), true);
        /** @var HtlCampScheduleResponse $htlCampSchedule */
        $htlCampSchedule = $this->queryBus->ask(new IndexHtlCampScheduleQuery($index->idHtlCampSchedule()->value()));

        $this->queryBus->ask(
            new AvailabilityHtlCampScheduleQuery(
                $htlCampSchedule->Id_HtlCamp,
                $index->dateStart()->value(),
                $query->amount() - $index->amount()->value()
            )
        );
        $lastAmount = $index->amount()->value();
        $index->setAmount(new HtlCampBookingAmount($query->amount()));

        $this->updater->__invoke($index);
        $this->queryBus->ask(new ChangeUsageHtlCampScheduleQuery($htlCampSchedule->Id_HtlCamp, $index->dateStart()->value(), $lastAmount, $index->amount()->value()));
    }
}
