<?php

namespace DigitalApps\PaymentsForAdyen;

defined('ABSPATH') || exit;

/** Resolve Checkout API URLs without allowing arbitrary hosts. */
final class Adyen_Endpoint_Resolver
{
	const CHECKOUT_API_VERSION = 'v71';

	/**
	 * Return the Checkout API base URL for an environment.
	 *
	 * @param bool   $test_mode Whether the test environment is active.
	 * @param string $live_url_prefix Prefix assigned in Adyen Customer Area.
	 * @return string
	 * @throws \InvalidArgumentException When a live prefix is missing or invalid.
	 */
	public static function checkout_base_url($test_mode, $live_url_prefix = '')
	{
		if ($test_mode) {
			return 'https://checkout-test.adyen.com/' . self::CHECKOUT_API_VERSION;
		}

		$prefix = strtolower(trim((string) $live_url_prefix));
		if (!self::is_valid_live_url_prefix($prefix)) {
			throw new \InvalidArgumentException('A valid Adyen live URL prefix is required.');
		}

		return 'https://' . $prefix . '-checkout-live.adyenpayments.com/checkout/' . self::CHECKOUT_API_VERSION;
	}

	/**
	 * Validate only the prefix, never a host or URL supplied by an administrator.
	 *
	 * @param string $prefix Candidate live URL prefix.
	 * @return bool
	 */
	public static function is_valid_live_url_prefix($prefix)
	{
		$prefix = trim((string) $prefix);
		return strlen($prefix) <= 128
			&& 1 === preg_match('/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/', $prefix);
	}
}
