<?php

namespace NoahVet\Reef\Paginator\Resolver;

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

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

    #[\Override]
    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');
            }
            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;
    }
}
