<?php

namespace App\Modules\PaxInformationRoom\Application\Insert;

use App\Http\History\HistoryTables;
use App\Modules\Location\Application\Find\FindLocationQuery;
use App\Modules\Location\Application\LocationResponse;
use App\Modules\Location\Domain\IdLocation;
use App\Modules\PaxInformationRoom\Domain\IdPaxInformationRoom;
use App\Modules\PaxInformationRoom\Domain\PaxInformationRoom;
use App\Modules\PaxInformationRoom\Domain\PaxInformationRoomDate;
use App\Modules\PaxInformationRoom\Domain\PaxInformationRoomDateUpdate;
use App\Modules\PaxInformationRoom\Domain\PaxInformationRoomDescription;
use App\Modules\PaxInformationRoom\Domain\PaxInformationRoomRepository;
use App\Modules\PaxInformationRoom\Domain\PaxInformationRoomStatus;
use App\Modules\PaxInformationRoom\Domain\PaxInformationRoomVersion;
use App\Modules\TypeApplication\Find\FindTypeDefinedServiceQuery;
use App\Modules\History\Application\Insert\InsertHistoryQuery;
use App\Modules\History\Domain\HistoryOperation;
use App\Modules\PaxInformation\Application\Find\FindPaxInformationQuery;
use App\Modules\PaxInformation\Domain\IdPaxInformation;
use App\Modules\Shared\Domain\Bus\Event\EventBus;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Domain\Transaction;
use App\Modules\TypeRoom\Application\Find\FindTypeRoomQuery;
use App\Modules\TypeRoom\Domain\IdTypeRoom;

final class PaxInformationRoomInserter
{
    public function __construct(
        private PaxInformationRoomRepository $repository,
        private EventBus $eventBus,
        private QueryBus $queryBus,
        private Transaction $transaction
    ) {}

    public function __invoke(
        IdPaxInformationRoom $id,
        PaxInformationRoomDate $date,
        PaxInformationRoomDateUpdate $dateUpdate,
        PaxInformationRoomVersion $version,
        PaxInformationRoomStatus $status,
        IdPaxInformation $idPaxInformation,
        IdTypeRoom $idTypeRoom,
        int $idAdmin
    ) {
        $this->queryBus->ask(new FindPaxInformationQuery($idPaxInformation->value()));
        $this->queryBus->ask(new FindTypeRoomQuery($idTypeRoom->value()));

        $this->transaction->begin();
        $model = PaxInformationRoom::create(
            $id,
            $date,
            $dateUpdate,
            $version,
            $status,
            $idPaxInformation,
            $idTypeRoom,
        );
        $id = $this->repository->insert($model);
        $model->setId($id);
        // $model->addCreatedDomainEvent($idAdmin);
        // $this->eventBus->publishAll(...$model->pullDomainEvents());
        $this->transaction->commit();
        $this->queryBus->ask(new InsertHistoryQuery(
            json_encode([]),
            json_encode([$model->toArray()]),
            HistoryOperation::INSERT,
            $id->value(),
            $id->value(),
            HistoryTables::PAX_INFORMATION_ROOM,
            $idAdmin,
        ));
        return $id->value();
    }
}
