<?php

namespace App\Http\Controllers\Owner\GroupProviderMedia;

use App\Http\Controllers\Controller;
use App\Modules\GroupProviderMedia\Application\GroupProviderMediaResponse;
use App\Modules\GroupProviderMedia\Application\Index\IndexGroupProviderMediaQuery;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Domain\Transaction;
use App\Providers\StorageProvider;

class GroupProviderMediaDownloadIndexController extends Controller
{
    private $domain;

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

    public function __invoke($Id)
    {
        $this->transaction->begin();
        /** @var GroupProviderMediaResponse $response */
        $response = $this->appendPrivatePath($this->queryBus->ask(new IndexGroupProviderMediaQuery($Id)));
        $this->transaction->commit();

        if (!file_exists($response->GroupProviderMedia_Path)) {
            abort(404);
        }
        return response()->download($response->GroupProviderMedia_Path);
    }

    public function appendPrivatePath($gpm)
    {
        $this->storage->appendPrivateToObject($gpm, 'GroupProviderMedia_Path');
        $this->storage->appendPrivateToObject($gpm, 'GroupProviderMedia_Path_Thumb');
        $this->storage->appendPrivateToObject($gpm, 'GroupProviderMedia_Path_LargeThumb');
        return $gpm;
    }
}
