<?php

namespace App\Traits;

trait RepositoryRelationshipsTraits
{
    /**
     * @var array|string[]
     */
    protected array $actualRelations;

    /**
     * @return array|string[]
     */
    public function getActualRelations(): array
    {
        return $this->actualRelations;
    }

    /**
     * remove relations for next query
     *
     * @param  array|string  &$relation  <p>
     *                                   The relation name or relations array.
     *                                   </p>
     * @param  mixed  ...$relations  [optional] <p>
     *                               The relations name.
     *                               </p>
     */
    public function removeRelation($relation, ...$relations): self
    {
        if (! is_array($relation)) {
            $relation = func_get_args();
        }
        $this->actualRelations = array_diff($this->actualRelations, $relation);

        return $this;
    }

    /**
     * add relations for next query
     *
     * @param  array|string  &$relation  <p>
     *                                   The relation name or relations array.
     *                                   </p>
     * @param  mixed  ...$relations  [optional] <p>
     *                               The relations name.
     *                               </p>
     */
    public function addRelation($relation, ...$relations): self
    {
        if (! is_array($relation)) {
            $relation = func_get_args();
        }
        $needToAdd = array_diff($relation, $this->actualRelations);
        foreach ($needToAdd as $newItem) {
            if (in_array($newItem, $this->getAvailableRelations())) {
                array_push($this->actualRelations, $newItem);
            }
        }

        return $this;
    }

    /**
     * set relations for next query
     *
     * @param  array|string  &$relation  <p>
     *                                   The relation name or relations array.
     *                                   </p>
     * @param  mixed  ...$relations  [optional] <p>
     *                               The relations name.
     *                               </p>
     */
    public function setRelation($relation, ...$relations): self
    {
        if (! is_array($relation)) {
            $relations = func_get_args();
        } else {
            $relations = $relation;
        }
        $this->actualRelations = [];
        foreach ($relations as $newItem) {
            $this->addRelation($newItem);
        }

        return $this;
    }

    /**
     * return available product relations
     */
    public function getAvailableRelations(): array
    {
        return $this->Model::getRelationshipsNames(true);
    }

    public function getQueryWithRelations(): \Illuminate\Database\Eloquent\Builder
    {
        return $this->Model::with($this->actualRelations);
    }
}
