<?php

namespace App\Modules\GroupPassenger\Application\DeleteMedia;

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

final class GroupPassengerMediaDeleter
{
    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'));

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

        return $response;
    }
}
