<?php

declare(strict_types=1);

namespace BookiFlex\Core\Debug;

use Psr\Log\LoggerInterface;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

defined('ABSPATH') || exit;

/**
 * Logs peak/current memory usage of every BookiFlex REST request to the debug log.
 *
 * Active only when WP_DEBUG is on (LoggerInterface min level is `debug` then).
 * Hooks into rest_post_dispatch — fires after the controller has produced the response.
 */
class RequestMemoryLogger
{
    public function __construct(
        private readonly LoggerInterface $logger
    ) {
    }

    public function register(): void
    {
        add_filter('rest_post_dispatch', [$this, 'onDispatch'], 10, 3);
    }

    /**
     * @param WP_REST_Response $result
     * @param WP_REST_Server $server
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function onDispatch($result, $server, $request)
    {
        if (!$request instanceof WP_REST_Request) {
            return $result;
        }

        $route = $request->get_route();
        if (!str_starts_with($route, '/bflex/')) {
            return $result;
        }

        $peakBytes    = memory_get_peak_usage(true);
        $currentBytes = memory_get_usage(true);

        $this->logger->debug('BookiFlex REST memory usage', [
            'route'      => $route,
            'method'     => $request->get_method(),
            'peak_mb'    => round($peakBytes / 1024 / 1024, 2),
            'current_mb' => round($currentBytes / 1024 / 1024, 2),
        ]);

        return $result;
    }
}
