<?php

namespace App\Modules\DefinedService\TypeDefinedService\Application\Update;

use App\Http\History\HistoryTables;
use App\Modules\DefinedService\TypeDefinedService\Domain\IdTypeDefinedService;
use App\Modules\DefinedService\TypeDefinedService\Domain\IndexTypeDefinedService;
use App\Modules\DefinedService\TypeDefinedService\Domain\TypeDefinedServiceCode;
use App\Modules\DefinedService\TypeDefinedService\Domain\TypeDefinedServiceName;
use App\Modules\DefinedService\TypeDefinedService\Domain\TypeDefinedServiceRepository;
use App\Modules\DefinedService\TypeDefinedService\Domain\TypeDefinedServiceStatus;
use App\Modules\DefinedService\TypeDefinedService\Domain\TypeDefinedServiceVersion;
use App\Modules\History\Application\Insert\InsertHistoryQuery;
use App\Modules\History\Domain\HistoryOperation;
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 TypeDefinedServiceUpdater
{
    public function __construct(
        private TypeDefinedServiceRepository $repository,
        private VersionChecker $versionChecker,
        private EventBus $eventBus,
        private QueryBus $queryBus,
        private Transaction $transaction
    ) {}

    public function __invoke(
        IdTypeDefinedService $id,
        TypeDefinedServiceName $name,
        TypeDefinedServiceCode $code,
        TypeDefinedServiceVersion $version,
        TypeDefinedServiceStatus $status,
        int $idAdmin
    ) {
        $this->transaction->begin();
        $index = $this->repository->find(new IndexTypeDefinedService($id));
        $lastData = $index->toArray();
        $this->versionChecker->__invoke($index, $version->value());
        $index->setName($name);
        $index->setCode($code);
        $index->setStatus($status);
        $index->updateVersion();
        $index->updateDateUpdate();
        $id = $this->repository->update($index);
        // $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::TYPE_DEFINED_SERVICE,
            $idAdmin,
        ));
        $this->transaction->commit();
    }
}
