<?php

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

use App\Http\History\HistoryTables;
use App\Modules\DefinedService\DefinedService\Domain\DefinedService;
use App\Modules\DefinedService\DefinedService\Domain\IdDefinedService;
use App\Modules\DefinedService\DefinedService\Domain\IndexDefinedService;
use App\Modules\DefinedService\DefinedService\Domain\DefinedServiceName;
use App\Modules\DefinedService\DefinedService\Domain\DefinedServiceRepository;
use App\Modules\DefinedService\DefinedService\Domain\DefinedServiceStatus;
use App\Modules\DefinedService\DefinedService\Domain\DefinedServiceVersion;
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 DefinedServiceUpdater
{
    public function __construct(
        private DefinedServiceRepository $repository,
        private VersionChecker $versionChecker,
        private EventBus $eventBus,
        private QueryBus $queryBus,
        private Transaction $transaction
    ) {}

    public function __invoke(
        IdDefinedService $id,
        DefinedServiceName $name,
        DefinedServiceVersion $version,
        DefinedServiceStatus $status,
        int $idAdmin
    ) {
        $this->transaction->begin();
        /** @var DefinedService $index */
        $index = $this->repository->find(new IndexDefinedService($id));
        $lastData = $index->toArray();
        $this->versionChecker->__invoke($index, $version->value());

        $index->setName($name);
        $index->setStatus($status);
        $index->updateVersion();
        $index->updateDateUpdate();
        $id = $this->repository->update($index);
        $this->queryBus->ask(new InsertHistoryQuery(
            json_encode([$lastData]),
            json_encode([$index->toArray()]),
            HistoryOperation::UPDATE,
            $index->id()->value(),
            $index->id()->value(),
            HistoryTables::DEFINED_SERVICE,
            $idAdmin,
        ));
        $this->transaction->commit();
    }
}
