<?php
declare(strict_types=1);

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

final class CommandHandlerDefinition
{
    public function __construct(
        private readonly string $handlerId,
        private readonly string $commandType,
        private readonly string $eventType,
        private readonly string $status = 'active',
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $handlerId, string $commandType, string $eventType): self
    {
        return new self($handlerId, $commandType, $eventType, 'active', date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['handlerId'] ?? ''),
            (string) ($data['commandType'] ?? ''),
            (string) ($data['eventType'] ?? ''),
            (string) ($data['status'] ?? 'active'),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function handlerId(): string { return $this->handlerId; }
    public function commandType(): string { return $this->commandType; }
    public function eventType(): string { return $this->eventType; }
    public function active(): bool { return $this->status === 'active'; }

    public function handles(CommandMessage $command): bool
    {
        return $this->active() && $this->commandType === $command->commandType();
    }

    public function toArray(): array
    {
        return [
            'handlerId' => $this->handlerId,
            'commandType' => $this->commandType,
            'eventType' => $this->eventType,
            'status' => $this->status,
            'active' => $this->active(),
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
