<?php

declare(strict_types=1);

namespace App\Application\Analytics\Service;

use App\Framework\Analytics\Storage\AnalyticsStorage;

/**
 * Service für Analytics Dashboard-Daten
 * Verantwortlich für: Zusammenfassung und Aufbereitung von Dashboard-Metriken
 */
final readonly class AnalyticsDashboardService
{
    public function __construct(
        private AnalyticsStorage $storage
    ) {
    }

    /**
     * @return array<string, int|float>
     */
    public function getOverview(string $startDate, string $endDate): array
    {
        $timeSeries = $this->storage->getTimeSeries('page_views_total', $startDate, $endDate, 'hour');
        $aggregatedData = $this->storage->getAggregated($startDate, $endDate, 'hour');

        $totalPageViews = array_sum(array_column($timeSeries, 'value'));

        // Falls keine Daten gefunden, schaue direkt in aggregierten Daten
        if ($totalPageViews === 0 && ! empty($aggregatedData)) {
            foreach ($aggregatedData as $period => $data) {
                if (isset($data['page_views_total'])) {
                    $totalPageViews += $data['page_views_total'];
                }
            }
        }

        // Berechne geschätzte Metriken basierend auf verfügbaren Daten
        $estimatedVisitors = (int) ($totalPageViews * 0.7); // 70% unique visitors
        $bounceRate = 0.35; // Geschätzte Absprungrate
        $conversionRate = 0.02; // Geschätzte Conversion Rate

        return [
            'total_page_views' => $totalPageViews,
            'unique_visitors' => $estimatedVisitors,
            'bounce_rate' => $bounceRate,
            'avg_session_duration' => 180.5,
            'conversion_rate' => $conversionRate,
            'error_rate' => 0.01,
        ];
    }

    /**
     * @return array<string, int>
     */
    public function getTopPages(string $startDate, string $endDate, int $limit = 10): array
    {
        // Hole alle aggregierten Daten und suche nach page_views_* Mustern
        $aggregatedData = $this->storage->getAggregated($startDate, $endDate, 'hour');

        $pageViews = [];
        foreach ($aggregatedData as $period => $data) {
            foreach ($data as $key => $value) {
                // Suche nach page_views_/path Pattern
                if (str_starts_with($key, 'page_views_/')) {
                    $path = substr($key, 11); // Remove 'page_views_' prefix
                    if (! isset($pageViews[$path])) {
                        $pageViews[$path] = 0;
                    }
                    $pageViews[$path] += (int)$value;
                }
            }
        }

        // Sortiere nach Views
        arsort($pageViews);

        // Formatiere für Ausgabe
        $topPages = [];
        foreach (array_slice($pageViews, 0, $limit, true) as $path => $views) {
            // Verwende deterministischen Wert basierend auf dem Pfad für konsistente Bounce-Rate
            $pathHash = crc32($path);
            $consistentBounceRate = 0.3 + (($pathHash % 21) / 100); // 0.30 bis 0.50

            $topPages[] = [
                'path' => $path,
                'views' => $views,
                'unique_visitors' => (int)($views * 0.7), // Schätzung
                'bounce_rate' => round($consistentBounceRate, 2),
            ];
        }

        return $topPages;
    }

    /**
     * @return array<string, int>
     */
    public function getTrafficSources(string $startDate, string $endDate): array
    {
        // Simuliere Traffic-Quellen
        return [
            'Direct' => 45,
            'Google' => 35,
            'Social Media' => 12,
            'Referral' => 8,
        ];
    }
}
