<?php

declare(strict_types=1);

namespace App\Base;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;

class ReadPageQueryBuilder
{
    /** @phpstan-ignore-next-line */
    public function __construct(public Builder $Qb, public ReadPageParameter $ReadPageParameter) {}

    public function addFilter(string $Key): self
    {
        $value = $this->ReadPageParameter->getFilterValue($Key);
        if (isset($value)) {
            $this->Qb->where($Key, $value);
        }

        return $this;
    }

    /**
     * @param  string[]  $Keyzz
     * @return $this
     */
    public function addFilterzz(array $Keyzz): self
    {
        foreach ($Keyzz as $Key) {
            $this->addFilter($Key);
        }

        return $this;
    }

    public function addSort(): self
    {
        $this->Qb->orderBy($this->ReadPageParameter->SortField, $this->ReadPageParameter->SortOrder);

        return $this;
    }

    /**
     * @return LengthAwarePaginator<Model>
     */
    public function paginate(): LengthAwarePaginator
    {
        return $this->Qb->paginate(
            $this->ReadPageParameter->PerPage,
            ['*'],
            'Page',
            $this->ReadPageParameter->Page,
        );
    }

    /**
     * @return Paginator<Model>
     */
    public function paginateSimple(): Paginator
    {
        return $this->Qb->simplePaginate(
            $this->ReadPageParameter->PerPage,
            ['*'],
            'Page',
            $this->ReadPageParameter->Page,
        );
    }
}
