<?php

declare(strict_types=1);

namespace SiteFort\Modules\Firewall\SearchTrust;

final class SearchTrustContext {
	public const VERSION = 1;
	public const BOOTSTRAP_CONSTANT = 'SITEFORT_WAF_SEARCH_TRUST_CONTEXT';

	/**
	 * @param array<string, mixed> $data
	 * @return array<string, mixed>
	 */
	public static function create( array $data = [] ): array {
		$context = [
			'version' => self::VERSION,
			'checked' => ! empty( $data['checked'] ),
			'eligible' => ! empty( $data['eligible'] ),
			'verified' => ! empty( $data['verified'] ),
			'exception' => ! empty( $data['exception'] ),
			'engine' => strtolower( trim( (string) ( $data['engine'] ?? '' ) ) ),
			'scope_hash' => trim( (string) ( $data['scope_hash'] ?? '' ) ),
			// verified|spoofed|indeterminate, or '' when no check ran.
			'status' => strtolower( trim( (string) ( $data['status'] ?? '' ) ) ),
		];

		if ( $context['exception'] || $context['verified'] ) {
			$context['exception'] = true;
			$context['checked'] = true;
			$context['eligible'] = true;
			$context['verified'] = true;
			$context['status'] = SearchTrustDnsVerifier::TRUST_VERIFIED;
		}

		return $context;
	}

	/**
	 * @param array<string, mixed> $data
	 * @return array<string, mixed>|null
	 */
	public static function from_array( array $data ): ?array {
		if ( (int) ( $data['version'] ?? 0 ) !== self::VERSION ) {
			return null;
		}

		return self::create( $data );
	}

	/**
	 * @return array<string, mixed>|null
	 */
	public static function from_bootstrap_constant(): ?array {
		if ( ! defined( self::BOOTSTRAP_CONSTANT ) ) {
			return null;
		}

		$value = constant( self::BOOTSTRAP_CONSTANT );
		if ( ! is_array( $value ) ) {
			return null;
		}

		return self::from_array( $value );
	}

	/**
	 * @param array<string, mixed> $context
	 */
	public static function matches_scope_hash( array $context, string $scope_hash ): bool {
		$scope_hash = trim( $scope_hash );
		$context_hash = trim( (string) ( $context['scope_hash'] ?? '' ) );
		if ( $scope_hash === '' || $context_hash === '' ) {
			return false;
		}

		return hash_equals( $scope_hash, $context_hash );
	}
}
