<?php

declare(strict_types=1);

namespace NoahVet\Reef\Paginator\Resolver;

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

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

        // First page by default
        return 0;
    }
}
