<?php

declare(strict_types=1);

namespace NoahVet\Reef\Paginator\Resolver;

use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\Request;

class LimitResolver implements LimitResolverInterface
{
    public function __construct(private readonly int $limit)
    {
    }

    public function resolve(Request $request): int
    {
        if (
            $request->query->has('limit')) {
            if (
                (int) $request->query->get('limit') <= $this->limit
                && 0 < (int) $request->query->get('limit')
            ) {
                return (int) $request->query->get('limit');
            } else {
                throw new BadRequestException(
                    \sprintf(
                        'Invalid limit query param with value : %s. The value should be between 1 and %s',
                        (int) $request->query->get('limit'),
                        $this->limit,
                    ),
                );
            }
        }

        // Limit by default
        return $this->limit;
    }
}
