<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Sourcing\Domain;

final class DomainEventListener
{
    public function __construct(
        private readonly string $listenerId,
        private readonly string $name,
        private readonly array $eventTypes = [],
        private readonly array $aggregateTypes = [],
        private readonly string $status = 'active',
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $listenerId, string $name, array $eventTypes = [], array $aggregateTypes = []): self
    {
        return new self($listenerId, $name, $eventTypes, $aggregateTypes, 'active', date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['listenerId'] ?? ''),
            (string) ($data['name'] ?? ''),
            (array) ($data['eventTypes'] ?? []),
            (array) ($data['aggregateTypes'] ?? []),
            (string) ($data['status'] ?? 'active'),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function listenerId(): string { return $this->listenerId; }
    public function name(): string { return $this->name; }
    public function active(): bool { return $this->status === 'active'; }

    public function listensTo(DomainEventEnvelope $event): bool
    {
        if (!$this->active()) {
            return false;
        }

        $eventTypeMatch = $this->eventTypes === [] || in_array($event->eventType(), $this->eventTypes, true);
        $aggregateTypeMatch = $this->aggregateTypes === [] || in_array($event->aggregateType(), $this->aggregateTypes, true);

        return $eventTypeMatch && $aggregateTypeMatch;
    }

    public function toArray(): array
    {
        return [
            'listenerId' => $this->listenerId,
            'name' => $this->name,
            'eventTypes' => $this->eventTypes,
            'aggregateTypes' => $this->aggregateTypes,
            'status' => $this->status,
            'active' => $this->active(),
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
