<?php

declare(strict_types=1);

namespace Plugin\tnt_mcp\adminmenu\Controller;

use Plugin\tnt_mcp\src\Mcp\Admin\RequestLogView;
use Plugin\tnt_mcp\src\Mcp\Observability\RequestLogger;

/**
 * "Anfrage-Protokoll" tab: viewer for the MCP request log (endpoint/tool, params summary, auth
 * mode, HTTP status, duration, timestamp), most recent first.
 */
final class RequestLog extends BaseAdminController
{
    private const VIEW_LIMIT = 200;

    public function render(): void
    {
        if (!$this->isAdmin()) {
            $this->notLoggedInNotice();

            return;
        }

        echo $this->fetch('request-log.tpl', $this->data());
    }

    /**
     * The template vars, separated from rendering so the "Aktivität" tab can compose this view.
     *
     * @return array<string, mixed>
     */
    public function data(): array
    {
        $entries = (new RequestLogger($this->db()))->recent(self::VIEW_LIMIT);

        return [
            // The template renders a view model, not raw rows: which cell the tool name belongs in
            // is a decision, and it is made once, in PHP. See {@see RequestLogView}.
            'entries' => RequestLogView::rows($entries),
            'limit'   => self::VIEW_LIMIT,
        ];
    }
}
