<?php

namespace App\Http\Controllers\Owner\GroupPassengerMedia;

use App\Http\Controllers\Controller;
use App\Modules\GroupPassengerMedia\Application\GroupPassengerMediaResponse;
use App\Modules\GroupPassengerMedia\Application\Index\IndexGroupPassengerMediaQuery;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Domain\Transaction;
use App\Providers\StorageProvider;

class GroupPassengerMediaDownloadIndexController extends Controller
{
    private $domain;

    public function __construct(
        private QueryBus $queryBus,
        private Transaction $transaction,
        private StorageProvider $storage
    ) {
        $this->domain = "GroupPassengerMedia";
    }

    public function __invoke($Id)
    {
        $this->transaction->begin();
        /** @var GroupPassengerMediaResponse $response */
        $response = self::appendPath($this->queryBus->ask(new IndexGroupPassengerMediaQuery($Id)));
        $this->transaction->commit();

        if (!file_exists($response->GroupPassengerMedia_Path)) {
            abort(404);
        }

        return response()->download($response->GroupPassengerMedia_Path);
    }

    public function appendPath($gpm)
    {
        $this->storage->appendPrivateToObject($gpm, 'GroupPassengerMedia_Path');
        $this->storage->appendPrivateToObject($gpm, 'GroupPassengerMedia_Path_Thumb');
        $this->storage->appendPrivateToObject($gpm, 'GroupPassengerMedia_Path_LargeThumb');
        return $gpm;
    }
}
