<?php

declare(strict_types=1);

namespace App\Framework\Sse\ValueObjects;

use App\Framework\Http\SseStreamInterface;

/**
 * SSE Connection Value Object
 *
 * Represents a single SSE connection with its metadata.
 */
final readonly class SseConnection
{
    /**
     * @param ConnectionId $connectionId Unique connection identifier
     * @param SseStreamInterface $stream The SSE stream for this connection
     * @param array<SseChannel> $channels Subscribed channels
     * @param ?string $userId User ID if authenticated
     * @param \DateTimeImmutable $connectedAt Connection timestamp
     * @param \DateTimeImmutable $lastHeartbeat Last heartbeat timestamp
     */
    public function __construct(
        public ConnectionId $connectionId,
        public SseStreamInterface $stream,
        public array $channels,
        public ?string $userId = null,
        public \DateTimeImmutable $connectedAt = new \DateTimeImmutable(),
        public \DateTimeImmutable $lastHeartbeat = new \DateTimeImmutable()
    ) {
        // Validate channels array contains only SseChannel instances
        foreach ($channels as $channel) {
            if (! $channel instanceof SseChannel) {
                throw new \InvalidArgumentException('Channels must be instances of SseChannel');
            }
        }
    }

    /**
     * Create a new connection with updated heartbeat
     */
    public function withHeartbeat(\DateTimeImmutable $timestamp = new \DateTimeImmutable()): self
    {
        return new self(
            connectionId: $this->connectionId,
            stream: $this->stream,
            channels: $this->channels,
            userId: $this->userId,
            connectedAt: $this->connectedAt,
            lastHeartbeat: $timestamp
        );
    }

    /**
     * Check if connection is still alive
     */
    public function isAlive(): bool
    {
        return $this->stream->isConnectionActive() && $this->stream->isActive();
    }

    /**
     * Check if connection needs a heartbeat
     */
    public function needsHeartbeat(int $heartbeatIntervalSeconds = 30): bool
    {
        $secondsSinceHeartbeat = (new \DateTimeImmutable())->getTimestamp() - $this->lastHeartbeat->getTimestamp();

        return $secondsSinceHeartbeat >= $heartbeatIntervalSeconds;
    }

    /**
     * Check if connection is subscribed to a channel
     */
    public function isSubscribedTo(SseChannel $channel): bool
    {
        foreach ($this->channels as $subscribedChannel) {
            if ($subscribedChannel->matches($channel)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Get connection age in seconds
     */
    public function getAge(): int
    {
        return (new \DateTimeImmutable())->getTimestamp() - $this->connectedAt->getTimestamp();
    }

    /**
     * Check if connection is authenticated
     */
    public function isAuthenticated(): bool
    {
        return $this->userId !== null;
    }

    /**
     * Get all subscribed channels as strings
     *
     * @return array<string>
     */
    public function getChannelNames(): array
    {
        return array_map(
            fn (SseChannel $channel) => $channel->toString(),
            $this->channels
        );
    }

    /**
     * Get connection info as array
     */
    public function toArray(): array
    {
        return [
            'connection_id' => $this->connectionId->toString(),
            'user_id' => $this->userId,
            'channels' => $this->getChannelNames(),
            'connected_at' => $this->connectedAt->format('Y-m-d H:i:s'),
            'last_heartbeat' => $this->lastHeartbeat->format('Y-m-d H:i:s'),
            'age_seconds' => $this->getAge(),
            'is_alive' => $this->isAlive(),
            'is_authenticated' => $this->isAuthenticated(),
        ];
    }
}
