<?php

namespace App\Modules\LodgingPlace\Application\Delete;

use App\Http\History\HistoryTables;
use App\Modules\LodgingPlace\Domain\IdLodgingPlace;
use App\Modules\LodgingPlace\Domain\IndexLodgingPlace;
use App\Modules\LodgingPlace\Domain\LodgingPlaceRepository;
use App\Modules\History\Application\Insert\InsertHistoryQuery;
use App\Modules\History\Domain\HistoryOperation;
use App\Modules\LodgingPlace\Domain\LodgingPlace;
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\Versioner\Application\Check\VersionChecker;

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

    public function __invoke(
        IdLodgingPlace $id,
        int $idAdmin
    ) {
        $this->transaction->begin();
        /** @var LodgingPlace $index */
        $index = $this->repository->find(new IndexLodgingPlace($id));
        $lastData = $index->toArray();
        $index->delete();
        $index->updateVersion();
        $this->repository->update($index);
        // $index->addUpdatedDomainEvent($idAdmin);
        // $this->eventBus->publishAll(...$index->pullDomainEvents());
        $this->queryBus->ask(new InsertHistoryQuery(
            json_encode([$lastData]),
            json_encode([]),
            HistoryOperation::DELETE,
            $index->id()->value(),
            $index->id()->value(),
            HistoryTables::LODGING_PLACE,
            $idAdmin,
        ));
        $this->transaction->commit();
    }
}
