<?php

declare(strict_types=1);

namespace App\Framework\Analytics;

final readonly class AnalyticsEvent
{
    public function __construct(
        public string $type,
        public string $name,
        public array $data = [],
        public array $context = [],
        public ?string $userId = null,
        public ?string $sessionId = null,
        public ?\DateTimeImmutable $timestamp = null
    ) {}

    public static function pageView(string $path, array $context = []): self
    {
        return new self(
            type: 'page_view',
            name: $path,
            context: $context,
            timestamp: new \DateTimeImmutable()
        );
    }

    public static function userAction(string $action, string $userId, array $data = []): self
    {
        return new self(
            type: 'user_action',
            name: $action,
            data: $data,
            userId: $userId,
            timestamp: new \DateTimeImmutable()
        );
    }

    public static function performance(string $metric, float $value, array $context = []): self
    {
        return new self(
            type: 'performance',
            name: $metric,
            data: ['value' => $value],
            context: $context,
            timestamp: new \DateTimeImmutable()
        );
    }

    public function withUserId(string $userId): self
    {
        return new self(
            $this->type,
            $this->name,
            $this->data,
            $this->context,
            $userId,
            $this->sessionId,
            $this->timestamp
        );
    }

    public function withSessionId(string $sessionId): self
    {
        return new self(
            $this->type,
            $this->name,
            $this->data,
            $this->context,
            $this->userId,
            $sessionId,
            $this->timestamp
        );
    }

    public function toArray(): array
    {
        return [
            'type' => $this->type,
            'name' => $this->name,
            'data' => $this->data,
            'context' => $this->context,
            'user_id' => $this->userId,
            'session_id' => $this->sessionId,
            'timestamp' => $this->timestamp?->format(\DateTimeInterface::ATOM)
        ];
    }
}
