<?php

declare(strict_types=1);

namespace ApiModel\Action;

use ApiModel\Infrastructure\Metrics\MetricsRegistry;
use ApiModel\Shared\Exceptions\NotFoundException;
use ApiModel\Shared\Exceptions\UnauthorizedException;
use Psr\Http\Message\ServerRequestInterface;

final class MetricsAction
{
    /** @return array<string, mixed> */
    public function snapshot(ServerRequestInterface $request): array
    {
        if (trim((string) ($_ENV['METRICS_ENABLED'] ?? 'true')) !== 'true') {
            throw new NotFoundException('Not Found');
        }

        $providedKey = trim($request->getHeaderLine('X-Metrics-Key'));
        $expectedKey = trim((string) ($_ENV['METRICS_SECRET'] ?? ''));

        if ($providedKey === '' || $expectedKey === '' || ! hash_equals($expectedKey, $providedKey)) {
            throw new UnauthorizedException('Unauthorized');
        }

        return MetricsRegistry::snapshot();
    }
}
