<?php

declare(strict_types=1);

namespace apexl\Io\requestHelper;

use apexl\Io\exceptions\ValidationException;
use Deprecated;
use Psr\Http\Message\ServerRequestInterface;
use function apexl\Io\container;

abstract readonly class requestHelper
{
    protected ?object $body;
    protected array $query;

    /**
     * @throws ValidationException
     */
    public function __construct(protected ServerRequestInterface $request)
    {
        $body = $request->getParsedBody();

        $this->query = $request->getQueryParams();

        $this->body = $body ? (object) $body : null;

        $this->validate();
    }

    /**
     * @throws ValidationException
     */
    public function validate(): void {}

    /**
     * @throws ValidationException
     */
    #[Deprecated (message: 'Use `apexl\Io\factories\RequestHelperFactory` instead`')]
    public static function factory(ServerRequestInterface $request): static
    {
        return container()->make(static::class, ['request' => $request]);
    }

    protected function bodyParam($name, $default = null)
    {
        return $this->body->{$name} ?? $default;
    }

    protected function query($name, $default = null)
    {
        return $this->query[$name] ?? $default;
    }

    /**
     * @throws ValidationException
     */
    protected function requireBody(string $key, ?string $message = null): void
    {
        if (empty($this->body->{$key})) {
            $message = $message ?? sprintf('%s is required', $key);

            throw new ValidationException($message);
        }
    }

    /**
     * @throws ValidationException
     */
    protected function requireQuery(string $key, ?string $message = null): void
    {
        if (empty($this->query[$key])) {
            $message = $message ?? sprintf('%s is required', $key);

            throw new ValidationException($message);
        }
    }
}
