<?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 Analytics Overview Statistics
 *
 * Returns aggregated statistics for the analytics dashboard:
 * - Total clicks, unique clicks, conversions
 * - Conversion rate
 */
final readonly class GetAnalyticsOverview
{
    public function __construct(
        private ClickStatisticsService $statisticsService
    ) {
    }

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

        $stats = $this->statisticsService->getOverviewStats($since);

        return new JsonResult([
            'success' => true,
            'data' => $stats,
            'timestamp' => Timestamp::now()->format('Y-m-d H:i:s'),
        ]);
    }

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