<?php

namespace App\Modules\HtlCampLock\Application\Create;

use App\Modules\HtlCamp\Domain\IdHtlCamp;
use App\Modules\HtlCampLock\Domain\IdHtlCampLock;
use App\Modules\HtlCampLock\Domain\HtlCampLock;
use App\Modules\HtlCampLock\Domain\HtlCampLockDate;
use App\Modules\HtlCampLock\Domain\HtlCampLockDateAlreadyLocked;
use App\Modules\HtlCampLock\Domain\HtlCampLockDateStart;
use App\Modules\HtlCampLock\Domain\HtlCampLockRemark;
use App\Modules\HtlCampLock\Domain\HtlCampLockStatus;
use App\Modules\HtlCampSchedule\Application\Find\FindHtlCampScheduleQuery;
use App\Modules\HtlCampSchedule\Application\HtlCampScheduleResponse;
use App\Modules\HtlCampSchedule\Application\UpdateLock\UpdateLockHtlCampScheduleCommand;
use App\Modules\HtlCampSchedule\Domain\HtlCampScheduleLock;
use App\Modules\HtlCampSchedule\Domain\IdHtlCampSchedule;
use App\Modules\Shared\Domain\Bus\Command\CommandBus;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Domain\Bus\Query\QueryHandler;
use App\Modules\Shared\Domain\ValueObject\DateTimeValueObject;

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

    public function __invoke(CreateHtlCampLockQuery $query): CreateHtlCampLockResponse
    {
        $idHtlCamp = new IdHtlCamp($query->idHtlCamp());
        $dateStart = new HtlCampLockDateStart($query->dateStart());
        // dd($dateStart->value(DateTimeValueObject::$format), $query->dateStart());
        /** @var HtlCampScheduleResponse $campSchedule */
        $campSchedule = $this->queryBus->ask(new FindHtlCampScheduleQuery(
            $idHtlCamp->value(),
            $dateStart->value(DateTimeValueObject::$format)
        ));

        if ($campSchedule->HtlCampSchedule_Lock === HtlCampScheduleLock::VALUE_TRUE) {
            throw new HtlCampLockDateAlreadyLocked();
        }

        $model = new HtlCampLock(
            new IdHtlCampLock(0),
            new HtlCampLockDate($query->date()),
            new HtlCampLockDateStart($query->dateStart()),
            new HtlCampLockRemark($query->remark()),
            new HtlCampLockStatus($query->status()),
            new IdHtlCampSchedule($campSchedule->Id_HtlCampSchedule),
        );
        $create = $this->creator->__invoke($model);
        if ($query->status() == HtlCampLockStatus::ACTIVE) {
            $this->commandBus->dispatch(new UpdateLockHtlCampScheduleCommand(
                $campSchedule->Id_HtlCampSchedule,
                HtlCampScheduleLock::VALUE_TRUE
            ));
        }
        return new CreateHtlCampLockResponse($create);
    }
}
