<?php

declare(strict_types=1);

namespace Webauthn\CeremonyStep;

use InvalidArgumentException;
use Webauthn\AuthenticationExtensions\AuthenticationExtensions;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
use function count;
use function in_array;
use function is_array;
use function is_string;
use function sprintf;
use function strlen;
use function substr;

final readonly class CheckAllowedOrigins implements CeremonyStep
{
    /**
     * Full origin entries (scheme://host[:port]) from allowed origins that include a scheme.
     *
     * @var string[]
     */
    private array $fullOrigins;

    /**
     * Host-only entries from allowed origins without a scheme (backward compatibility).
     *
     * @var string[]
     */
    private array $hostOrigins;

    /**
     * @param string[] $allowedOrigins
     */
    public function __construct(
        array $allowedOrigins,
        private bool $allowSubdomains = false
    ) {
        $fullOrigins = [];
        $hostOrigins = [];
        foreach ($allowedOrigins as $allowedOrigin) {
            $parsed = parse_url($allowedOrigin);
            $parsed !== false || throw new InvalidArgumentException(sprintf('Invalid origin: %s', $allowedOrigin));
            if (isset($parsed['scheme'], $parsed['host'])) {
                $fullOrigins[] = self::buildOrigin($parsed['scheme'], $parsed['host'], $parsed['port'] ?? null);
            } else {
                $hostOrigins[] = $parsed['host'] ?? $allowedOrigin;
            }
        }

        $this->fullOrigins = array_unique($fullOrigins);
        $this->hostOrigins = array_unique($hostOrigins);
    }

    public function process(
        PublicKeyCredentialSource $publicKeyCredentialSource,
        AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
        PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
        ?string $userHandle,
        string $host
    ): void {
        $authData = $authenticatorResponse instanceof AuthenticatorAssertionResponse ? $authenticatorResponse->authenticatorData : $authenticatorResponse->attestationObject->authData;
        $C = $authenticatorResponse->clientDataJSON;

        $parsedOrigin = parse_url($C->origin);
        is_array($parsedOrigin) || throw AuthenticatorResponseVerificationException::create(
            'Invalid origin. Unable to parse the origin.'
        );
        $originHost = $parsedOrigin['host'] ?? $C->origin;

        $hasAllowedOrigins = count($this->fullOrigins) !== 0 || count($this->hostOrigins) !== 0;

        if ($hasAllowedOrigins) {
            // Full origin match (scheme + host + port)
            if (isset($parsedOrigin['scheme'], $parsedOrigin['host'])) {
                $normalizedOrigin = self::buildOrigin(
                    $parsedOrigin['scheme'],
                    $parsedOrigin['host'],
                    $parsedOrigin['port'] ?? null
                );
                if (in_array($normalizedOrigin, $this->fullOrigins, true)) {
                    return;
                }
            }

            // Host-only match (backward compatibility for entries without scheme)
            if (in_array($originHost, $this->hostOrigins, true)) {
                return;
            }

            // Subdomain matching
            $isFullOriginSubdomain = $this->isSubdomainOfFullOrigins($parsedOrigin);
            $isHostSubdomain = $this->isSubdomain($this->hostOrigins, $originHost);
            $isSubDomain = $isFullOriginSubdomain || $isHostSubdomain;

            if ($this->allowSubdomains && $isSubDomain) {
                return;
            }
            if (! $this->allowSubdomains && $isSubDomain) {
                throw AuthenticatorResponseVerificationException::create('Invalid origin. Subdomains are not allowed.');
            }
            throw AuthenticatorResponseVerificationException::create(
                'Invalid origin. Not in the list of allowed origins.'
            );
        }

        $rpId = $publicKeyCredentialOptions->rpId ?? $publicKeyCredentialOptions->rp->id ?? $host;
        $facetId = $this->getFacetId($rpId, $publicKeyCredentialOptions->extensions, $authData->extensions);
        $facetId !== '' || throw AuthenticatorResponseVerificationException::create(
            'Invalid origin. Unable to determine the facet ID.'
        );
        if ($originHost === $facetId) {
            return;
        }
        $isSubDomains = $this->isSubdomainOf($originHost, $facetId);
        if ($this->allowSubdomains && $isSubDomains) {
            return;
        }
        if (! $this->allowSubdomains && $isSubDomains) {
            throw AuthenticatorResponseVerificationException::create('Invalid origin. Subdomains are not allowed.');
        }

        $scheme = $parsedOrigin['scheme'] ?? '';
        $scheme === 'https' || throw AuthenticatorResponseVerificationException::create(
            'Invalid scheme. HTTPS required.'
        );
    }

    /**
     * @param array<string, mixed> $parsedOrigin Parsed origin from parse_url()
     */
    private function isSubdomainOfFullOrigins(array $parsedOrigin): bool
    {
        if (! isset($parsedOrigin['scheme'], $parsedOrigin['host'])) {
            return false;
        }
        /** @var string $originScheme */
        $originScheme = $parsedOrigin['scheme'];
        /** @var string $originHost */
        $originHost = $parsedOrigin['host'];
        $originPort = $parsedOrigin['port'] ?? null;

        foreach ($this->fullOrigins as $fullOrigin) {
            $parsedAllowed = parse_url($fullOrigin);
            if (! is_array($parsedAllowed) || ! isset($parsedAllowed['scheme'], $parsedAllowed['host'])) {
                continue;
            }
            /** @var string $allowedScheme */
            $allowedScheme = $parsedAllowed['scheme'];
            /** @var string $allowedHost */
            $allowedHost = $parsedAllowed['host'];
            if ($originScheme !== $allowedScheme) {
                continue;
            }
            $allowedPort = $parsedAllowed['port'] ?? null;
            if ($originPort !== $allowedPort) {
                continue;
            }
            if ($this->isSubdomainOf($originHost, $allowedHost)) {
                return true;
            }
        }

        return false;
    }

    private static function buildOrigin(string $scheme, string $host, ?int $port): string
    {
        if ($port === null) {
            return sprintf('%s://%s', $scheme, $host);
        }
        $defaultPorts = [
            'https' => 443,
            'http' => 80,
        ];
        if (isset($defaultPorts[$scheme]) && $port === $defaultPorts[$scheme]) {
            return sprintf('%s://%s', $scheme, $host);
        }
        return sprintf('%s://%s:%d', $scheme, $host, $port);
    }

    private function isSubdomainOf(string $subdomain, string $domain): bool
    {
        return substr('.' . $subdomain, -strlen('.' . $domain)) === '.' . $domain;
    }

    private function getFacetId(
        string $rpId,
        AuthenticationExtensions $AuthenticationExtensions,
        ?AuthenticationExtensions $authenticationExtensionsClientOutputs
    ): string {
        if ($authenticationExtensionsClientOutputs === null
            || ! $AuthenticationExtensions->has('appid')
            || ! $authenticationExtensionsClientOutputs->has('appid')) {
            return $rpId;
        }

        $appId = $AuthenticationExtensions->get('appid')
            ->value;
        $wasUsed = $authenticationExtensionsClientOutputs->get('appid')
            ->value;

        return (is_string($appId) && $wasUsed === true) ? $appId : $rpId;
    }

    /**
     * @param string[] $origins
     */
    private function isSubdomain(array $origins, string $domain): bool
    {
        foreach ($origins as $allowedOrigin) {
            if ($this->isSubdomainOf($domain, $allowedOrigin)) {
                return true;
            }
        }
        return false;
    }
}
