<?php

namespace App\Modules\GroupProvider\Application\DeleteMedia;

use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\GroupProvider\Domain\GroupProvider;
use App\Modules\GroupProvider\Domain\IdGroupProvider;
use App\Modules\GroupProvider\Domain\GroupProviderRepository;
use App\Modules\GroupProvider\Domain\GroupProviderMediaStatus;
use App\Modules\GroupProvider\Domain\GroupProviderMediaDateUpdate;
use App\Modules\GroupProvider\Application\Index\GroupProviderIndexer;
use App\Modules\GroupProviderMedia\Application\Delete\DeleteGroupProviderMediaQuery;
use App\Modules\GroupProviderMedia\Application\GroupProviderMediaResponses;
use App\Modules\GroupProviderMedia\Application\List\ListGroupProviderMediaQuery;

final class GroupProviderMediaDeleter
{
    public function __construct(
        private GroupProviderRepository $repository,
        private GroupProviderIndexer $groupPassengerIndexer,
        private QueryBus $queryBus
    ) {
    }

    public function __invoke(IdGroupProvider $id): GroupProviderMediaResponses
    {
        /** @var GroupProvider $index */
        $index = $this->groupPassengerIndexer->__invoke($id);
        $index->setMediaStatus(new GroupProviderMediaStatus(GroupProviderMediaStatus::DOWNLOADED));
        $index->setMediaDateUpdate(GroupProviderMediaDateUpdate::reduceDatetimeToPeru(GroupProviderMediaDateUpdate::now()));
        $this->repository->updateModel($index);
        /** @var GroupProviderMediaResponses $response */
        $response = $this->queryBus->ask(new ListGroupProviderMediaQuery($index->id()->value(), 'active'));

        foreach ($response->data() as $media) {
            $this->queryBus->ask(new DeleteGroupProviderMediaQuery($media->Id_GroupProviderMedia));
        }

        return $response;
    }
}
