<?php

declare(strict_types=1);

/**
 * APO-197 Card 4 — Read the audit log.
 *
 * URI:   GET /api/v1/system/audit-log
 * Scope: administration.read · exposeToMcp:FALSE
 *
 * Audit-log access via MCP would create a feedback loop (AI examines its
 * own request history). Operator-only.
 */
final class MyronGetAuditLogAction implements MyronAction
{
    public function __construct(
        private readonly MyronAuditLogRepository $repository,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/system/audit-log',
            method:        'GET',
            domain:        'system',
            resource:      'audit-log',
            verb:          'list',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'integrationId' => ['type' => 'string'],
                    'actionVerb'    => ['type' => 'string'],
                    'outcome'       => ['type' => 'string'],
                    'fromDate'      => ['type' => 'string'],
                    'toDate'        => ['type' => 'string'],
                    'limit'         => ['type' => 'integer'],
                    'offset'        => ['type' => 'integer'],
                ],
            ],
            outputSchema:  ['type' => 'object', 'properties' => ['items' => ['type' => 'array']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_READ,
            summary:       'Paginated audit log: who called what action when, sanitised input/output, outcome. Operator-only.',
            sideEffects:   [],
            preconditions: [],
            postconditions: [],
            audienceClass: 3,
            adminAliases:  [],
            snapshotInclude: false,
            exposeToMcp:   false,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $limit = (int) ($input['limit'] ?? 50);
        $offset = (int) ($input['offset'] ?? 0);
        $events = $this->repository->list($limit, $offset, $input);
        $items = array_map(static fn (MyronAuditEvent $e): array => $e->toArray(), $events);
        return MyronActionResult::ok(['items' => $items]);
    }
}
