<?php

declare(strict_types=1);

namespace SiteFort\Includes;

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

/**
 * RequestVerifier - Verifies v3 signed requests (HMAC + replay protection).
 *
 * Used for Console -> Plugin instant command delivery.
 */
class RequestVerifier {
	private const SIGNATURE_VERSION = '3';
	private const TIMEOUT_SECONDS   = 300; // 5 minutes
	private const TABLE_SUFFIX      = 'sitefort_request_nonces';

	private static bool $table_ready = false;

	/**
	 * Verify a signed request and enforce replay protection.
	 *
	 * @param string $site_token_expected Site token stored locally.
	 * @param string $site_secret         Site secret stored locally.
	 * @param string $method              HTTP method.
	 * @param string $request_uri         Full request URI (path + query).
	 * @param string $body               Raw request body.
	 * @param array<string,string> $headers Normalized header map (lowercase keys).
	 * @param int $max_body_bytes Optional maximum body size before hashing.
	 * @return true|\WP_Error
	 */
	public static function verify(
		string $site_token_expected,
		string $site_secret,
		string $method,
		string $request_uri,
		string $body,
		array $headers,
		int $max_body_bytes = 0
	) {
		if ( $site_token_expected === '' || $site_secret === '' ) {
			return new \WP_Error( 'not_linked', 'Site is not linked to console.', [ 'status' => 403 ] );
		}

		if ( $max_body_bytes > 0 && strlen( $body ) > $max_body_bytes ) {
			return new \WP_Error( 'payload_too_large', 'Request body is too large.', [ 'status' => 413 ] );
		}

		$site_token = (string) ( $headers['x-site-token'] ?? '' );
		if ( $site_token === '' || ! hash_equals( $site_token_expected, $site_token ) ) {
			return new \WP_Error( 'invalid_site_token', 'Invalid site token.', [ 'status' => 403 ] );
		}

		$signature         = (string) ( $headers['x-request-signature'] ?? '' );
		$timestamp         = (string) ( $headers['x-request-timestamp'] ?? '' );
		$signature_version = (string) ( $headers['x-request-signature-version'] ?? '' );
		$nonce             = (string) ( $headers['x-request-nonce'] ?? '' );
		$request_id        = (string) ( $headers['x-request-id'] ?? '' );
		$body_hash         = (string) ( $headers['x-request-body-hash'] ?? '' );

		if ( $signature === '' || $timestamp === '' || $signature_version === '' || $nonce === '' || $request_id === '' || $body_hash === '' ) {
			return new \WP_Error( 'missing_signature', 'Missing signature headers.', [ 'status' => 401 ] );
		}
		if ( $signature_version !== self::SIGNATURE_VERSION ) {
			return new \WP_Error( 'unsupported_signature', 'Unsupported signature version.', [ 'status' => 401 ] );
		}

		if ( strlen( $signature ) > 128 || strlen( $nonce ) > 128 || strlen( $request_id ) > 128 || strlen( $body_hash ) > 128 ) {
			return new \WP_Error( 'invalid_signature', 'Invalid signature header length.', [ 'status' => 401 ] );
		}

		$req_id_ok = function_exists( 'wp_is_uuid' ) ? wp_is_uuid( $request_id ) : ( preg_match( '/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $request_id ) === 1 );
		if ( ! $req_id_ok ) {
			return new \WP_Error( 'invalid_request_id', 'Invalid request id.', [ 'status' => 401 ] );
		}

		if ( ! ctype_digit( $timestamp ) ) {
			return new \WP_Error( 'invalid_timestamp', 'Invalid timestamp.', [ 'status' => 401 ] );
		}
		$ts = (int) $timestamp;
		if ( abs( time() - $ts ) > self::TIMEOUT_SECONDS ) {
			return new \WP_Error( 'expired', 'Request timestamp expired.', [ 'status' => 401 ] );
		}

		$actual_body_hash = hash( 'sha256', $body );
		if ( ! hash_equals( $body_hash, $actual_body_hash ) ) {
			return new \WP_Error( 'body_hash_mismatch', 'Body hash mismatch.', [ 'status' => 401 ] );
		}

		$path  = (string) ( wp_parse_url( $request_uri, PHP_URL_PATH ) ?: '/' );
		$query = (string) ( wp_parse_url( $request_uri, PHP_URL_QUERY ) ?: '' );

		$payload = self::build_canonical_payload( strtoupper( $method ), $path, $query, $timestamp, $nonce, $request_id, $body_hash );
		$expected = hash_hmac( 'sha256', $payload, $site_secret );
		if ( ! hash_equals( $expected, $signature ) ) {
			return new \WP_Error( 'invalid_signature', 'Invalid request signature.', [ 'status' => 403 ] );
		}

		// Replay protection (nonce + request_id).
		self::ensure_table();
		if ( ! self::check_and_store_nonce( $site_token_expected, $nonce, $request_id ) ) {
			return new \WP_Error( 'replay', 'Replay detected.', [ 'status' => 403 ] );
		}

		return true;
	}

	/**
	 * Verify a signed WP REST request using the same v3 canonical contract.
	 *
	 * @param string           $site_token_expected Site token stored locally.
	 * @param string           $site_secret         Site secret stored locally.
	 * @param \WP_REST_Request $request             REST request.
	 * @param int              $max_body_bytes Optional maximum body size before hashing.
	 * @return true|\WP_Error
	 */
	public static function verify_rest_request( string $site_token_expected, string $site_secret, $request, int $max_body_bytes = 0 ) {
		if ( $max_body_bytes > 0 ) {
			$content_length = isset( $_SERVER['CONTENT_LENGTH'] ) && ! is_array( $_SERVER['CONTENT_LENGTH'] ) ? (string) wp_unslash( $_SERVER['CONTENT_LENGTH'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Numeric length is validated before use.
			if ( '' !== $content_length && ( ! ctype_digit( $content_length ) || (int) $content_length > $max_body_bytes ) ) {
				return new \WP_Error( 'payload_too_large', 'Request body is too large.', [ 'status' => 413 ] );
			}
		}

		$raw = $request->get_headers();
		$headers = [];
		foreach ( $raw as $key => $values ) {
			$key = str_replace( '_', '-', strtolower( (string) $key ) );
			$headers[ $key ] = is_array( $values ) ? (string) ( $values[0] ?? '' ) : (string) $values;
		}

		$method = (string) $request->get_method();
		$uri    = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_unslash( $_SERVER['REQUEST_URI'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Raw URI is required for HMAC canonicalization; it is validated before use.
		if ( '' === $uri || strlen( $uri ) > 4096 || preg_match( '/[\x00-\x20\x7F]/', $uri ) ) {
			return new \WP_Error( 'invalid_request_uri', 'Invalid request URI.', [ 'status' => 401 ] );
		}
		$body   = (string) $request->get_body();

		return self::verify( $site_token_expected, $site_secret, $method, $uri, $body, $headers, $max_body_bytes );
	}

	/**
	 * Option key that gates DDL to run only once (set after first successful CREATE).
	 * Schema is stable so no version-keying is needed; clearing this option forces
	 * a re-create (e.g. after manual table drop).
	 */
	private const TABLE_READY_OPTION = 'sitefort_nonce_table_v1';

	public static function ensure_table_schema(): bool {
		self::ensure_table();

		return self::$table_ready;
	}

	public static function is_table_schema_current(): bool {
		global $wpdb;

		$table = $wpdb->prefix . self::TABLE_SUFFIX;
		if (
			! \SiteFort\Core\Database\SchemaInspector::table_exists( $table )
			|| ! \SiteFort\Core\Database\SchemaInspector::table_engine_ready( $table )
		) {
			return false;
		}

		foreach ( [ 'site_token', 'nonce', 'request_id' ] as $column ) {
			if ( ! \SiteFort\Core\Database\SchemaInspector::column_uses_collation( $table, $column, 'ascii_bin' ) ) {
				return false;
			}
		}

		return true;
	}

	/**
	 * @return void
	 */
	private static function ensure_table(): void {
		if ( self::$table_ready ) {
			return;
		}

		if ( get_option( self::TABLE_READY_OPTION ) !== false ) {
			if ( self::table_exists() ) {
				global $wpdb;
				$table = $wpdb->prefix . self::TABLE_SUFFIX;
				if ( self::ensure_portable_table_schema( $table ) ) {
					self::$table_ready = true;
					return;
				}
			}
			delete_option( self::TABLE_READY_OPTION );
		}

		global $wpdb;
		$table = $wpdb->prefix . self::TABLE_SUFFIX;
		$charset_collate = \SiteFort\Core\Database\SchemaInspector::validated_charset_collate( $wpdb );

		$sql = "CREATE TABLE IF NOT EXISTS {$table} (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			site_token varchar(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
			nonce varchar(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
			request_id varchar(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
			created_at int(10) unsigned NOT NULL,
			PRIMARY KEY  (id),
			UNIQUE KEY uk_site_nonce (site_token, nonce),
			UNIQUE KEY uk_site_request (site_token, request_id),
			KEY idx_created (created_at)
		) {$charset_collate};";

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQL.NotPrepared -- Creates a plugin-owned replay-protection table; placeholders are not supported for SQL identifiers or DDL.
		$wpdb->query( $sql );
		\SiteFort\Core\Database\SchemaInspector::flush_cache( $table );

		if ( self::table_exists() ) {
			if ( self::ensure_portable_table_schema( $table ) ) {
				update_option( self::TABLE_READY_OPTION, 1, true );
				self::$table_ready = true;
				return;
			}
		}

		sitefort_log(
			'[SiteFort] Request nonce table provisioning failed'
			. ( $wpdb->last_error !== '' ? ': ' . sanitize_text_field( $wpdb->last_error ) : '' )
		);
	}

	private static function ensure_portable_table_schema( string $table ): bool {
		if ( ! \SiteFort\Core\Database\SchemaInspector::table_exists( $table ) ) {
			return false;
		}

		$columns_ok = self::ensure_ascii_columns( $table );
		$engine_ok = \SiteFort\Core\Database\SchemaInspector::ensure_table_uses_innodb( $table );

		return $engine_ok && $columns_ok;
	}

	private static function ensure_ascii_columns( string $table ): bool {
		global $wpdb;

		$columns = [ 'site_token', 'nonce', 'request_id' ];
		$all_ok = true;
		$table_identifier = self::table_identifier( $table );

		foreach ( $columns as $column ) {
			if ( \SiteFort\Core\Database\SchemaInspector::column_uses_collation( $table, $column, 'ascii_bin' ) ) {
				continue;
			}

			$column_identifier = '`' . str_replace( '`', '``', $column ) . '`';
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Repairs plugin-owned replay columns to portable indexed ASCII strings.
			$result = $wpdb->query( "ALTER TABLE {$table_identifier} MODIFY {$column_identifier} varchar(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL" );
			\SiteFort\Core\Database\SchemaInspector::flush_cache( $table );

			if ( false === $result ) {
				sitefort_log( '[SiteFort] Request nonce table column repair failed for ' . $column . ': ' . $wpdb->last_error );
				$all_ok = false;
				continue;
			}

			if ( ! \SiteFort\Core\Database\SchemaInspector::column_uses_collation( $table, $column, 'ascii_bin' ) ) {
				sitefort_log( '[SiteFort] Request nonce table column repair did not produce ascii_bin for ' . $column . '.' );
				$all_ok = false;
			}
		}

		return $all_ok;
	}

	/**
	 * @return bool
	 */
	private static function table_exists(): bool {
		global $wpdb;
		$table = $wpdb->prefix . self::TABLE_SUFFIX;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Runs only once per process when the ready option exists.
		$found = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
		return is_string( $found ) && strtolower( $found ) === strtolower( $table );
	}

	/**
	 * @return bool
	 */
	private static function check_and_store_nonce( string $site_token, string $nonce, string $request_id ): bool {
		global $wpdb;
		$table = self::table_identifier( $wpdb->prefix . self::TABLE_SUFFIX );
		$cutoff = time() - self::TIMEOUT_SECONDS;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Deletes expired rows from a plugin-owned replay table using an escaped identifier.
		$wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE created_at < %d", $cutoff ) );

		$now = time();
		// Use INSERT IGNORE to handle unique constraint without leaking state.
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$sql = $wpdb->prepare(
			"INSERT IGNORE INTO {$table} (site_token, nonce, request_id, created_at) VALUES (%s, %s, %s, %d)",
			$site_token,
			$nonce,
			$request_id,
			$now
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Executes the prepared insert statement assembled above for a plugin-owned replay table.
		$result = $wpdb->query( $sql );
		return (int) $result === 1;
	}

	/**
	 * Escape a plugin-owned table identifier for direct interpolation.
	 */
	private static function table_identifier( string $table ): string {
		if ( $table === '' || strlen( $table ) > 64 || ! preg_match( '/^[A-Za-z0-9_]+$/', $table ) ) {
			throw new \InvalidArgumentException( 'Invalid table identifier.' );
		}

		return '`' . str_replace( '`', '``', $table ) . '`';
	}

	private static function build_canonical_payload(
		string $method,
		string $path,
		string $query,
		string $timestamp,
		string $nonce,
		string $request_id,
		string $body_hash
	): string {
		$canonical_query = self::canonicalize_query( $query );
		$normalized_path = self::normalize_path( $path );
		return implode(
			"\n",
			[
				$method,
				$normalized_path,
				$canonical_query,
				$timestamp,
				$nonce,
				$request_id,
				$body_hash,
			]
		);
	}

	/**
	 * Normalize a URL path: collapse '//', resolve '..', ensure leading '/'.
	 */
	private static function normalize_path( string $path ): string {
		if ( $path === '' ) {
			return '/';
		}

		// Decode unreserved percent-encoded characters (RFC 3986 2.3).
		$path = preg_replace_callback(
			'/%([0-9A-Fa-f]{2})/',
			static function ( array $m ): string {
				$char = chr( (int) hexdec( $m[1] ) );
				// Unreserved: A-Z a-z 0-9 - . _ ~
				if ( ctype_alnum( $char ) || strpos( '-._~', $char ) !== false ) {
					return $char;
				}
				return strtoupper( $m[0] );
			},
			$path
		);

		// Collapse consecutive slashes.
		$path = preg_replace( '#/{2,}#', '/', $path );

		// Resolve '..' and '.' segments.
		$segments = explode( '/', $path );
		$stack    = [];
		foreach ( $segments as $seg ) {
			if ( $seg === '..' ) {
				array_pop( $stack );
			} elseif ( $seg !== '.' && $seg !== '' ) {
				$stack[] = $seg;
			}
		}

		return '/' . implode( '/', $stack );
	}

	public static function canonicalize_query( string $query ): string {
		if ( $query === '' ) {
			return '';
		}
		$pairs = [];
		foreach ( explode( '&', $query ) as $segment ) {
			if ( $segment === '' ) {
				continue;
			}
			$kv = explode( '=', $segment, 2 );
			$key = urldecode( $kv[0] );
			$value = urldecode( $kv[1] ?? '' );
			$pairs[] = [ rawurlencode( $key ), rawurlencode( $value ) ];
		}
		usort(
			$pairs,
			static function ( $a, $b ) {
				if ( $a[0] === $b[0] ) {
					return $a[1] <=> $b[1];
				}
				return $a[0] <=> $b[0];
			}
		);
		$out = [];
		foreach ( $pairs as $p ) {
			$out[] = $p[0] . '=' . $p[1];
		}
		return implode( '&', $out );
	}
}
