<?php

declare(strict_types=1);

namespace App\Application\SmartLink\Api;

use App\Domain\SmartLink\Services\ClickStatisticsService;
use App\Framework\Attributes\Route;
use App\Framework\Core\ValueObjects\Timestamp;
use App\Framework\Http\HttpRequest;
use App\Framework\Http\Method;
use App\Framework\Router\Result\JsonResult;

/**
 * Get Top Performing SmartLinks
 *
 * Returns list of top performing links by click count
 */
final readonly class GetTopPerformingLinks
{
    public function __construct(
        private ClickStatisticsService $statisticsService
    ) {
    }

    #[Route(path: '/api/analytics/top-links', method: Method::GET)]
    public function __invoke(HttpRequest $request): JsonResult
    {
        $limit = (int) $request->queryParameters->get('limit', '10');
        $limit = min(max($limit, 1), 100); // Limit to 1-100

        $range = $request->queryParameters->get('range', '24h');
        $since = $this->parseTimeRange($range);

        $topLinks = $this->statisticsService->getTopPerformingLinks($limit, $since);

        return new JsonResult([
            'success' => true,
            'data' => $topLinks,
            'meta' => [
                'limit' => $limit,
                'range' => $range,
                'count' => count($topLinks),
            ],
        ]);
    }

    private function parseTimeRange(string $range): ?Timestamp
    {
        $now = Timestamp::now();

        return match ($range) {
            '1h' => $now->subtractHours(1),
            '24h' => $now->subtractHours(24),
            '7d' => $now->subtractDays(7),
            '30d' => $now->subtractDays(30),
            'all' => null,
            default => $now->subtractHours(24),
        };
    }
}
