<?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;

/**
 * Class ZiskatZoznamInformaciiAction
 */
final class ZiskatZoznamInformaciiAction extends BaseController
{
    /**
     * @var int
     */
    public const PER_PAGE = 15;

    private InformaciaRepositoryContract $informaciaRepository;

    public function __construct(InformaciaRepositoryContract $informaciaRepository)
    {
        $this->informaciaRepository = $informaciaRepository;
    }

    /**
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function __invoke(): Response
    {
        try {
            $limit = ($limit = (int) request()->get('limit', self::PER_PAGE)) > 50 ? 50 : $limit;
            $sort = request()->get('sort', 'desc');

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

            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í.');
        }
    }
}
