<?php

namespace App\Modules\GroupPassenger\Application\DownloadMedia;

use App\Modules\GroupPassenger\Application\Index\GroupPassengerIndexer;
use App\Modules\GroupPassenger\Domain\GroupPassengerMediaDateUpdate;
use App\Modules\GroupPassenger\Domain\GroupPassengerMediaStatus;
use App\Modules\GroupPassenger\Domain\GroupPassengerModel;
use App\Modules\GroupPassenger\Domain\GroupPassengerRepository;
use App\Modules\GroupPassenger\Domain\IdGroupPassenger;
use App\Modules\GroupPassengerMedia\Application\GroupPassengerMediaResponses;
use App\Modules\GroupPassengerMedia\Application\List\ListGroupPassengerMediaQuery;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;

final class GroupPassengerMediaDownloader
{
    public function __construct(
        private GroupPassengerRepository $repository,
        private GroupPassengerIndexer $groupPassengerIndexer,
        private QueryBus $queryBus
    ) {
    }

    public function __invoke(IdGroupPassenger $id): GroupPassengerMediaResponses
    {
        /** @var GroupPassengerModel $index */
        $index = $this->groupPassengerIndexer->__invoke($id);
        $index->setMediaStatus(new GroupPassengerMediaStatus(GroupPassengerMediaStatus::DOWNLOADED));
        $index->setMediaDateUpdate(GroupPassengerMediaDateUpdate::reduceDatetimeToPeru(GroupPassengerMediaDateUpdate::now()));
        $this->repository->updateModel($index);
        /** @var GroupPassengerMediaResponses $response */
        $response = $this->queryBus->ask(new ListGroupPassengerMediaQuery($index->id()->value(), 'active'));
        return $response;
    }
}
