<?php

namespace App\Modules\HtlCampLock\Application\Create;

use App\Modules\BookingTour\Domain\IdBookingTour;
use App\Modules\HtlCampLock\Domain\IdHtlCampLock;
use App\Modules\HtlCampLock\Domain\HtlCampLock;
use App\Modules\HtlCampLock\Domain\HtlCampLockAmount;
use App\Modules\HtlCampLock\Domain\HtlCampLockDate;
use App\Modules\HtlCampLock\Domain\HtlCampLockDateStart;
use App\Modules\HtlCampLock\Domain\HtlCampLockLock;
use App\Modules\HtlCampLock\Domain\HtlCampLockRemark;
use App\Modules\HtlCampLock\Domain\HtlCampLockStatus;
use App\Modules\HtlCampSchedule\Application\AddUsage\AddUsageHtlCampScheduleQuery;
use App\Modules\HtlCampSchedule\Application\Availability\AvailabilityHtlCampScheduleQuery;
use App\Modules\HtlCampSchedule\Application\HtlCampScheduleResponse;
use App\Modules\HtlCampSchedule\Domain\IdHtlCampSchedule;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Domain\Bus\Query\QueryHandler;

final class CreateHtlCampLockQueryHandler implements QueryHandler
{
    public function __construct(
        private HtlCampLockCreator $creator,
        private QueryBus $queryBus
    ) {
    }

    public function __invoke(CreateHtlCampLockQuery $query): CreateHtlCampLockResponse
    {
        /** @var HtlCampScheduleResponse $campSchedule */
        $campSchedule = $this->queryBus->ask(new AvailabilityHtlCampScheduleQuery($query->idHtlCamp(), $query->dateStart(), $query->amount()));

        $model = new HtlCampLock(
            new IdHtlCampLock(0),
            new HtlCampLockDate($query->date()),
            new HtlCampLockDateStart($query->dateStart()),
            new HtlCampLockAmount($query->amount()),
            new HtlCampLockStatus($query->status()),
            new IdHtlCampSchedule($campSchedule->Id_HtlCampSchedule),
        );
        $create = $this->creator->__invoke($model);
        if ($query->status() == HtlCampLockStatus::PENDING) {
            $this->queryBus->ask(new AddUsageHtlCampScheduleQuery($query->idHtlCamp(), $query->dateStart(), $query->amount()));
        }
        return new CreateHtlCampLockResponse($create);
    }
}
