<?php

namespace LaraBB\Post\Tasks;

use Closure;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use LaraBB\Post\Models\Post;

/**
 * Class GetThreadTask
 * @package LaraBB\Thread\Tasks
 */
class FindTask
{
    /**
     * @var Builder|null $query
     */
    private ?Builder $query;
    /**
     * @var string
     */
    private string $return = 'Collection';

    /**
     * GetThreadTask constructor.
     * @param Post $post
     */
    public function __construct(private readonly Post $post)
    {

    }


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

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

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

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


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

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