<?php

namespace App\Http\Controllers\API\V1\Informacia\Frontend;

use App\Http\Controllers\API\BaseController;
use App\Repositories\Eloquent\Criteria\AnyRolePouzivatelaCriteria;
use App\Repositories\Eloquent\Criteria\OrderByCasZverejneniaAscCriteria;
use App\Repositories\Eloquent\Criteria\OrderByCasZverejneniaDescCriteria;
use App\Repositories\Eloquent\Criteria\ZverejneneCriteria;
use App\Repositories\InformaciaRepositoryContract;
use Dingo\Api\Http\Response;
use Exception;
use Prettus\Repository\Exceptions\RepositoryException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * Class ZiskatZoznamInformaciiAction
 *
 * @package App\Http\Controllers\API\V1\Informacia\Frontend
 */
final class ZiskatZoznamInformaciiAction extends BaseController
{
    /**
     * @var int
     */
    public const PER_PAGE = 15;

    /**
     * @var InformaciaRepositoryContract
     */
    private InformaciaRepositoryContract $informaciaRepository;

    /**
     * @param InformaciaRepositoryContract $informaciaRepository
     */
    public function __construct(InformaciaRepositoryContract $informaciaRepository)
    {
        $this->informaciaRepository = $informaciaRepository;
    }

    /**
     * @return Response|void
     * @throws RepositoryException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function __invoke(): Response
    {
        try {
            $sort = request()->get('sort', 'desc');

            $informacie = $this->informaciaRepository
                ->pushCriteria(ZverejneneCriteria::class)
                ->pushCriteria(AnyRolePouzivatelaCriteria::class)
                ->pushCriteria(
                    ($sort != 'desc') ? OrderByCasZverejneniaAscCriteria::class : OrderByCasZverejneniaDescCriteria::class,
                )
                ->with('vytvoril')
                ->paginate(self::PER_PAGE);

            if ($informacie->isEmpty()) {
                return $this->response->noContent();
            }

            return $this->response->paginator($informacie);
        } catch (Exception $e) {
            $this->response->errorInternal('Nepodarilo sa získať zoznam informácií.');
        }
    }
}
