<?php

namespace LaraBB\Settings\Tasks\Prefix;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use LaraBB\Settings\Models\Prefix;

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

    /**
     * GetPrefixTask constructor.
     * @param Prefix $prefix
     */
    public function __construct(private readonly Prefix $prefix)
    {
    }

    /**
     * @param array $with
     * @return Collection|Prefix|null
     */
    public function run(array $with = []): Collection|Prefix|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 Collection|Prefix|null
     */
    public function byUuid($uuid, array $with = []): Collection|Prefix|null
    {
        $this->return = 'Model';
        $this->query  = $this->prefix->query()->where('uuid', $uuid);

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