<?php
declare(strict_types=1);

namespace Wohno\Plugin\Support;

use const Wohno\Plugin\DEFAULT_API_BASE;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Central plugin configuration helpers.
 *
 * The single source of truth for the Wohno API base URL — resolves the
 * `WOHNO_API_BASE` override (wp-config.php) and **enforces HTTPS**. A non-HTTPS
 * override is refused (falls back to the secure default) except for obvious
 * local-development hosts, so a misconfiguration can never downgrade the
 * server-to-server call carrying the secret API key to plaintext.
 */
final class Config {

	/**
	 * The validated API base URL (no trailing slash, HTTPS-enforced).
	 *
	 * @return string
	 */
	public static function api_base(): string {
		$raw = defined( 'WOHNO_API_BASE' ) ? (string) constant( 'WOHNO_API_BASE' ) : DEFAULT_API_BASE;

		return self::normalize( $raw );
	}

	/**
	 * Normalise + HTTPS-validate a base URL. Pure (no constants/options) so it
	 * is fully unit-testable.
	 *
	 * @param string $raw Candidate base URL.
	 * @return string A trimmed, slash-trimmed HTTPS URL, or the secure default
	 *                if the candidate is empty or not HTTPS (non-local).
	 */
	public static function normalize( string $raw ): string {
		$base = untrailingslashit( trim( $raw ) );
		if ( '' === $base ) {
			return DEFAULT_API_BASE;
		}

		$scheme = strtolower( (string) wp_parse_url( $base, PHP_URL_SCHEME ) );
		$host   = strtolower( (string) wp_parse_url( $base, PHP_URL_HOST ) );

		if ( 'https' === $scheme ) {
			return $base;
		}
		// Allow plain HTTP only for unmistakable local-dev hosts.
		if ( 'http' === $scheme && self::is_local_host( $host ) ) {
			return $base;
		}

		// Anything else (http to a public host, ftp://, missing scheme, …) is
		// refused — never downgrade the key-bearing request.
		return DEFAULT_API_BASE;
	}

	/**
	 * Whether a host is an obvious local-development host.
	 *
	 * @param string $host Lower-cased hostname.
	 * @return bool
	 */
	private static function is_local_host( string $host ): bool {
		if ( in_array( $host, array( 'localhost', '127.0.0.1', '::1' ), true ) ) {
			return true;
		}

		return str_ends_with( $host, '.test' )
			|| str_ends_with( $host, '.local' )
			|| str_ends_with( $host, '.localhost' );
	}
}
