<?php

declare(strict_types=1);

namespace App\Service;

use App\Repository\SignalRepository;
use DateTimeImmutable;
use DateTimeZone;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

final readonly class SignalSnapshotService
{
    public function __construct(
        private SignalRepository $signals,
        private SignalSnapshotBuilder $snapshotBuilder,
        #[Autowire('%app.signal_snapshot_limit%')] private int $snapshotLimit,
        #[Autowire(service: 'monolog.logger.signals')] private LoggerInterface $logger,
    ) {
    }

    public function buildSnapshot(?int $limit, string $clientKey): array
    {
        $resolvedLimit = $this->normalizeLimit($limit);
        $signals = $this->signals->findRecent($resolvedLimit);
        $snapshot = $this->snapshotBuilder->build($signals);

        $this->logger->info('Built signal snapshot for client.', [
            'client_key' => $clientKey,
            'requested_limit' => $limit,
            'applied_limit' => $resolvedLimit,
            'point_count' => count($snapshot['points']),
        ]);

        return [
            'clientKey' => $clientKey,
            'points' => $snapshot['points'],
            'density' => $snapshot['density'],
            'latestByUser' => $snapshot['latestByUser'],
            'totals' => $snapshot['totals'],
            'updatedAt' => new DateTimeImmutable('now', new DateTimeZone('UTC'))->format(DATE_ATOM),
        ];
    }

    private function normalizeLimit(?int $limit): int
    {
        if ($limit === null) {
            return $this->snapshotLimit;
        }

        if ($limit < 1) {
            return $this->snapshotLimit;
        }

        return min($limit, $this->snapshotLimit);
    }
}
