<?php

namespace LaraBB\Torrent\Actions;

use LaraBB\Torrent\UI\Web\Requests\DownloadRequest;
use LaraBB\Torrent\Tasks\FindTask as FindTorrentTask;
use Rhilip\Bencode\TorrentFile;
use Storage;

/**
 *
 */
class DownloadAction
{
    /**
     * @param FindTorrentTask $findTorrentTask
     */
    public function __construct(
        private readonly FindTorrentTask $findTorrentTask
    ) {

    }

    /**
     * @param DownloadRequest $request
     * @return array|null
     */
    public function run(DownloadRequest $request): ?array
    {
        $torrent = $this->findTorrentTask->byUuid($request->route('uuid'));

        if(Storage::fileExists($torrent->filename)) {
            $torrentFile = TorrentFile::load(storage_path('app/' . $torrent->filename));
            $torrentFile->setAnnounce($torrentFile->getAnnounce() . '/' . $request->user()->pid);

            return [
                'torrentFile' => $torrentFile,
                'filename'    => $torrent->name
            ];
        }

        return null;
    }
}
