<?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 Device Type Distribution Statistics
 *
 * Returns click distribution by device type (mobile, desktop, tablet)
 */
final readonly class GetDeviceStatistics
{
    public function __construct(
        private ClickStatisticsService $statisticsService
    ) {
    }

    #[Route(path: '/api/analytics/devices', method: Method::GET)]
    public function __invoke(HttpRequest $request): JsonResult
    {
        $range = $request->queryParameters->get('range', '24h');
        $since = $this->parseTimeRange($range);

        $distribution = $this->statisticsService->getDeviceDistribution($since);

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

    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),
        };
    }
}
