<?php

namespace LaraBB\Torrent\Actions;

use Illuminate\Database\Connection;
use LaraBB\Torrent\Models\Torrent;
use LaraBB\Torrent\Tasks\StoreTask as StoreTorrentTask;
use LaraBB\Torrent\UI\Web\Requests\StoreRequest;
use Rhilip\Bencode\TorrentFile;
use Storage;
use Throwable;

/**
 *
 */
class StoreAction
{
    private Torrent $torrent;

    /**
     * @param StoreTorrentTask $storeTorrentTask
     * @param Connection $connection
     */
    public function __construct(
        private readonly StoreTorrentTask $storeTorrentTask,
        private readonly Connection $connection
    ) {

    }

    /**
     * @param StoreRequest $request
     * @return bool|Torrent
     */
    public function run(StoreRequest $request): bool|Torrent
    {
        try {
            $this->connection->transaction(function() use($request) {
                $this->torrent = $this->storeTorrentTask->run($this->prepareTorrentData($request));
            });
        } catch (Throwable $t) {
            return false;
        }

        return $this->torrent;
    }

    /**
     * @param $request
     * @return array
     */
    private function prepareTorrentData($request): array
    {
        $torrent = TorrentFile::load($request->file('torrent'));

        return [
            'created_uuid' => $request->user()->uuid,
            'updated_uuid' => $request->user()->uuid,
            'infohash'     => $torrent->getInfoHash(),
            'name'         => $torrent->getName(),
            'filename'     => $request->file('torrent')->store('torrents'),
            'size'         => $torrent->getSize(),
        ];
    }
}
