<?php

namespace Waypoint\Agent\Auth;

class Bearer_Auth {

	public function get_token(): string {
		$token = get_option( WAYPOINT_MONITOR_OPTION_TOKEN );
		if ( ! is_string( $token ) || strlen( $token ) < 32 ) {
			$token = bin2hex( random_bytes( 32 ) );
			update_option( WAYPOINT_MONITOR_OPTION_TOKEN, $token, false );
		}
		return $token;
	}

	public function permission_check( \WP_REST_Request $request ): bool|\WP_Error {
		$auth  = $request->get_header( 'Authorization' );
		$token = $this->get_token();
		if ( ! is_string( $auth ) || strpos( $auth, 'Bearer ' ) !== 0 ) {
			return new \WP_Error( 'waypoint_monitor_unauthorized', 'Missing bearer token', [ 'status' => 401 ] );
		}
		$presented = trim( substr( $auth, 7 ) );
		if ( ! hash_equals( $token, $presented ) ) {
			return new \WP_Error( 'waypoint_monitor_unauthorized', 'Invalid bearer token', [ 'status' => 401 ] );
		}
		return true;
	}
}
