<?php

declare(strict_types=1);

/*
 * Copyright (c) 2017-2023 François Kooman <fkooman@tuxed.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace fkooman\OAuth\Server\Http;

use fkooman\OAuth\Server\Exception\InvalidRequestException;
use fkooman\OAuth\Server\Scope;

class Post
{
    private array $postData;

    public function __construct(array $postData)
    {
        $this->postData = $postData;
    }

    public function clientId(): ?string
    {
        if (null === $clientId = $this->optionalParameter('client_id')) {
            return null;
        }

        // client-id  = *VSCHAR
        // VSCHAR     = %x20-7E
        if (1 !== preg_match('/^[\x20-\x7E]+$/', $clientId)) {
            throw new InvalidRequestException('invalid "client_id"');
        }

        return $clientId;
    }

    public function code(): string
    {
        $code = $this->requireParameter('code');

        // code       = 1*VSCHAR
        // VSCHAR     = %x20-7E
        if (1 !== preg_match('/^[\x20-\x7E]+$/', $code)) {
            throw new InvalidRequestException('invalid "code"');
        }

        return $code;
    }

    public function codeVerifier(): string
    {
        $codeVerifier = $this->requireParameter('code_verifier');

        // code-verifier = 43*128unreserved
        // unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
        // ALPHA         = %x41-5A / %x61-7A
        // DIGIT         = %x30-39
        if (1 !== preg_match('/^[\x41-\x5A\x61-\x7A\x30-\x39-._~]{43,128}$/', $codeVerifier)) {
            throw new InvalidRequestException('invalid "code_verifier"');
        }

        return $codeVerifier;
    }

    public function grantType(): string
    {
        $grantType = $this->requireParameter('grant_type');

        // grant-type = grant-name / URI-reference
        // grant-name = 1*name-char
        // name-char  = "-" / "." / "_" / DIGIT / ALPHA

        // we have an explicit allow list here instead of matching regexp
        if (!\in_array($grantType, ['authorization_code', 'refresh_token'], true)) {
            throw new InvalidRequestException('invalid "grant_type"');
        }

        return $grantType;
    }

    public function redirectUri(): string
    {
        // NOTE: no need to validate the redirect_uri, as we do strict string
        // comparison
        return $this->requireParameter('redirect_uri');
    }

    public function refreshToken(): string
    {
        $refreshToken = $this->requireParameter('refresh_token');

        // refresh-token = 1*VSCHAR
        // VSCHAR        = %x20-7E
        if (1 !== preg_match('/^[\x20-\x7E]+$/', $refreshToken)) {
            throw new InvalidRequestException('invalid "refresh_token"');
        }

        return $refreshToken;
    }

    public function scope(): ?Scope
    {
        // scope is optional for POST to token endpoint
        if (null === $scope = $this->optionalParameter('scope')) {
            return null;
        }

        return new Scope($scope);
    }

    public function approve(): string
    {
        $approve = $this->requireParameter('approve');

        // we only accept "yes" or "no"
        if (!\in_array($approve, ['yes', 'no'], true)) {
            throw new InvalidRequestException('invalid "approve"');
        }

        return $approve;
    }

    private function requireParameter(string $parameterName): string
    {
        if (!\array_key_exists($parameterName, $this->postData)) {
            throw new InvalidRequestException(sprintf('missing "%s" parameter', $parameterName));
        }

        if (!\is_string($this->postData[$parameterName])) {
            throw new InvalidRequestException(sprintf('"%s" parameter MUST be string', $parameterName));
        }

        return $this->postData[$parameterName];
    }

    private function optionalParameter(string $parameterName): ?string
    {
        if (!\array_key_exists($parameterName, $this->postData)) {
            return null;
        }

        if (!\is_string($this->postData[$parameterName])) {
            throw new InvalidRequestException(sprintf('"%s" parameter MUST be string', $parameterName));
        }

        return $this->postData[$parameterName];
    }
}
