<?php

declare(strict_types=1);

namespace App\Framework\Database\Events;

use App\Framework\Core\ValueObjects\Timestamp;

/**
 * Event that is fired when an entity is updated
 */
final readonly class EntityUpdatedEvent
{
    public Timestamp $timestamp;

    public function __construct(
        public object $entity,
        public string $entityClass,
        public mixed $entityId,
        public array $changes = [],
        public array $oldValues = [],
        public array $newValues = [],
        ?Timestamp $timestamp = null
    ) {
        $this->timestamp = $timestamp ?? Timestamp::now();
    }

    /**
     * Check if this event is for a specific entity class
     */
    public function isEntityOfType(string $expectedClass): bool
    {
        return $this->entityClass === $expectedClass || $this->entity instanceof $expectedClass;
    }

    /**
     * Check if a specific field was changed
     */
    public function hasFieldChanged(string $fieldName): bool
    {
        return in_array($fieldName, $this->changes, true);
    }

    /**
     * Get the old value of a field
     */
    public function getOldValue(string $fieldName): mixed
    {
        return $this->oldValues[$fieldName] ?? null;
    }

    /**
     * Get the new value of a field
     */
    public function getNewValue(string $fieldName): mixed
    {
        return $this->newValues[$fieldName] ?? null;
    }

    /**
     * Get event metadata
     */
    public function getEventData(): array
    {
        return [
            'event_type' => 'entity_updated',
            'entity_class' => $this->entityClass,
            'entity_id' => $this->entityId,
            'timestamp' => $this->timestamp->toFloat(),
            'changes' => $this->changes,
            'changed_fields_count' => count($this->changes),
        ];
    }
}
