<?php

declare(strict_types=1);

namespace Bot\Infrastructure\Repository;

use Bot\Domain\Entity\AnalyticsEvent;
use Bot\Domain\Repository\AnalyticsRepositoryInterface;

/**
 * پیاده‌سازی in-memory برای رخدادهای آنالیتیکس.
 */
final class InMemoryAnalyticsRepository implements AnalyticsRepositoryInterface
{
    /** @var AnalyticsEvent[] */
    private array $events = [];

    public function save(AnalyticsEvent $event): void
    {
        $this->events[] = $event;
    }

    /**
     * @return AnalyticsEvent[]
     */
    public function findByType(string $type): array
    {
        return array_filter($this->events, fn($event) => $event->getType() === $type);
    }

    /**
     * @return AnalyticsEvent[]
     */
    public function findByMediaId(int $mediaId): array
    {
        return array_filter($this->events, fn($event) => $event->getMediaId() === $mediaId);
    }

    /**
     * @return AnalyticsEvent[]
     */
    public function findByUserId(int $userId): array
    {
        return array_filter($this->events, fn($event) => $event->getUserId() === $userId);
    }

    /**
     * @return AnalyticsEvent[]
     */
    public function getAll(): array
    {
        return $this->events;
    }

    /**
     * @return AnalyticsEvent[]
     */
    public function findByDateRange(\DateTimeImmutable $startDate, \DateTimeImmutable $endDate): array
    {
        return array_filter($this->events, function ($event) use ($startDate, $endDate) {
            $occurredAt = $event->getOccurredAt();
            return $occurredAt >= $startDate && $occurredAt <= $endDate;
        });
    }

    /**
     * @return AnalyticsEvent[]
     */
    public function findByUserIdAndDateRange(int $userId, \DateTimeImmutable $startDate, \DateTimeImmutable $endDate): array
    {
        return array_filter($this->events, function ($event) use ($userId, $startDate, $endDate) {
            if ($event->getUserId() !== $userId) {
                return false;
            }
            $occurredAt = $event->getOccurredAt();
            return $occurredAt >= $startDate && $occurredAt <= $endDate;
        });
    }
}


