<?php

namespace LaraBB\Torrent\Tasks;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use LaraBB\Torrent\Models\Torrent;

/**
 *
 */
class FindTask
{
    /**
     * @var string
     */
    private string $return = 'Collection';

    /**
     * @var Torrent
     */
    private Torrent $torrent;

    /**
     * @var Builder|null
     */
    private ?Builder $query;

    /**
     * @param Torrent $torrent
     */
    public function __construct(Torrent $torrent)
    {
        $this->torrent = $torrent;
    }

    /**
     * @param array $with
     * @return Builder[]|Torrent|Collection|null
     */
    public function run(array $with = []): Collection|array|Torrent|null
    {
        if (is_null($this->query)) {
            $this->query = $this->torrent->query();
        }

        /** @var Collection $return */
        $data = $this->query->with($with)->get();

        if(is_null($data)) {
            return null;
        }

        return $this->return == 'Model' ? $data->first() : $data;
    }

    /**
     * @param $uuid
     * @param $with
     * @return Collection|array|Torrent|null
     */
    public function byUuid($uuid, $with = []): Collection|array|Torrent|null
    {
        $this->return = 'Model';
        $this->query  = $this->torrent->query()->where('uuid', $uuid);

        return $this->run($with);
    }

    /**
     * @param $infoHash
     * @param array $with
     * @return array|Collection|Torrent|null
     */
    public function byInfoHash($infoHash, array $with = []): Collection|array|Torrent|null
    {
        $this->return = 'Model';
        $this->query  = $this->torrent->query()->where('infohash', $infoHash);

        return $this->run($with);
    }
}
