<?php

namespace Infrastructure\Services\Utilities;

use App\Enums\SortDirectionEnum;
use Illuminate\Database\Eloquent\Builder;

abstract class Utility
{
    protected Builder $builder;
    protected string $sortKey = 'sorts';
    public function applyOnBuilder(Builder $builder): Builder
    {
        $this->builder = $builder;
        $this->applyFilters($builder);
        $this->applySorts($builder);

        return $builder;
    }

    private function applyFilters(Builder $builder): void
    {
        foreach ($this->filters() as $filterClass) {
            if (is_null($filterClass::key())) {
                continue;
            }
            if (request()->filled($filterKey = $filterClass::key())) {
                $filterClass::query($builder, request()->input($filterKey));
            }
        }
    }

    abstract protected function filters(): array;

    private function applySorts(Builder $builder): void
    {
        if (!request()->filled($this->sortKey) || !is_array(request()->input($this->sortKey))) {
            return;
        }
        foreach (request()->input($this->sortKey) as $sort) {
            if (!in_array($sort['field'] ?? '', $this->sorts()))
                continue;

            $builder->orderBy($sort['field'], $sort['direction'] ?? SortDirectionEnum::default());
        }
    }

    protected function sorts(): array
    {
        return [];
    }
    public function exportKeys(): array
    {
        return [];
    }
}
