<?php

declare(strict_types=1);

namespace App\Framework\Analytics\Storage;

final class FileAnalyticsStorage implements AnalyticsStorageInterface
{
    public function __construct(
        private readonly string $storagePath
    ) {
        if (!is_dir($this->storagePath)) {
            mkdir($this->storagePath, 0755, true);
        }
    }

    public function store(array $eventData): void
    {
        $date = date('Y-m-d');
        $filename = $this->storagePath . "/analytics-{$date}.jsonl";

        $line = json_encode($eventData) . "\n";
        file_put_contents($filename, $line, FILE_APPEND | LOCK_EX);
    }

    public function query(array $filters = []): array
    {
        // Einfache Implementation - kann erweitert werden
        $files = glob($this->storagePath . '/analytics-*.jsonl');
        $events = [];

        foreach ($files as $file) {
            $lines = file($file, FILE_IGNORE_NEW_LINES);
            foreach ($lines as $line) {
                $event = json_decode($line, true);
                if ($this->matchesFilters($event, $filters)) {
                    $events[] = $event;
                }
            }
        }

        return $events;
    }

    public function aggregate(string $metric, array $filters = []): array
    {
        $events = $this->query($filters);

        // Einfache Aggregation - kann erweitert werden
        $aggregated = [];
        foreach ($events as $event) {
            $key = $event['type'] ?? 'unknown';
            $aggregated[$key] = ($aggregated[$key] ?? 0) + 1;
        }

        return $aggregated;
    }

    private function matchesFilters(array $event, array $filters): bool
    {
        foreach ($filters as $key => $value) {
            if (!isset($event[$key]) || $event[$key] !== $value) {
                return false;
            }
        }
        return true;
    }
}
