<?php

namespace LaraBB\Peer\Tasks;

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


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


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

    /**
     * @param Peer $peer
     */
    public function __construct(private readonly Peer $peer)
    {
    }

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

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

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

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

    /**
     * @param $peer_id
     * @param $torrentUuid
     * @param array $with
     * @return Peer|Collection|null
     */
    public function byPeerIdAndTorrentUuid($peer_id, $torrentUuid, array $with = []): Peer|Collection|null
    {
        $this->return = 'Model';
        $this->query  = $this->peer->query()->where([
            ['peer_id', '=', $peer_id],
            ['torrent_uuid', '=', $torrentUuid]
        ]);

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

    /**
     * @param $torrentUuid
     * @param array $with
     * @return Collection|null
     */
    public function byTorrentUuid($torrentUuid, array $with = []): Collection|null
    {
        $this->return = 'Collection';
        $this->query = $this->peer->query()->where('torrent_uuid', $torrentUuid);

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