<?php

namespace App\Modules\PaxInformationRoom\Application\Update;

use App\Http\History\HistoryTables;
use App\Modules\PaxInformationRoom\Application\Index\IndexPaxInformationRoomPopulate;
use App\Modules\PaxInformationRoom\Domain\IdPaxInformationRoom;
use App\Modules\PaxInformationRoom\Domain\IndexPaxInformationRoom;
use App\Modules\PaxInformationRoom\Domain\PaxInformationRoomRepository;
use App\Modules\PaxInformationRoom\Domain\PaxInformationRoomStatus;
use App\Modules\PaxInformationRoom\Domain\PaxInformationRoomVersion;
use App\Modules\History\Application\Insert\InsertHistoryQuery;
use App\Modules\History\Domain\HistoryOperation;
use App\Modules\Room\Application\UpdateFromPaxInformation\UpdateFromPaxInformationRoomQuery;
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\Domain\IdTypeRoom;
use App\Modules\Versioner\Application\Check\VersionChecker;

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

    public function __invoke(
        IdPaxInformationRoom $id,
        PaxInformationRoomVersion $version,
        PaxInformationRoomStatus $status,
        IdTypeRoom $idTypeRoom,
        int $idAdmin
    ) {
        $this->transaction->begin();
        $index = $this->repository->find(new IndexPaxInformationRoom($id, new IndexPaxInformationRoomPopulate('')));
        $lastData = $index->toArray();
        // $this->versionChecker->__invoke($index, $version->value());
        if ($status->value() >= 0) {
            $index->setStatus($status);
        }
        $index->setIdTypeRoom($idTypeRoom);
        $index->updateVersion();
        $index->updateDateUpdate();
        $id = $this->repository->update($index);
        $this->queryBus->ask(new UpdateFromPaxInformationRoomQuery(
            $index->id()->value(),
            $index->status()->value(),
            $index->idTypeRoom()->value()
        ));
        // $index->addUpdatedDomainEvent($idAdmin);
        // $this->eventBus->publishAll(...$index->pullDomainEvents());
        $this->queryBus->ask(new InsertHistoryQuery(
            json_encode([$lastData]),
            json_encode([$index->toArray()]),
            HistoryOperation::UPDATE,
            $index->id()->value(),
            $index->id()->value(),
            HistoryTables::PAX_INFORMATION_ROOM,
            $idAdmin,
        ));
        $this->transaction->commit();
    }
}
