<?php

declare(strict_types=1);

namespace App\EventSubscriber;

use App\Entity\CustomFieldValue;
use App\Entity\Machine;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Events;

#[AsDoctrineListener(event: Events::onFlush)]
final class MachineAuditSubscriber extends AbstractAuditSubscriber
{
    protected function supports(object $entity): bool
    {
        return $entity instanceof Machine;
    }

    protected function entityType(): string
    {
        return 'machine';
    }

    protected function hasCollectionTracking(): bool
    {
        return true;
    }

    protected function getOwnerFromCustomFieldValue(CustomFieldValue $cfv): ?object
    {
        $owner = $cfv->getMachine();

        return $owner instanceof Machine ? $owner : null;
    }

    protected function snapshotEntity(object $entity): array
    {
        return [
            'id'              => $entity->getId(),
            'name'            => $this->safeGet($entity, 'getName'),
            'reference'       => $this->safeGet($entity, 'getReference'),
            'prix'            => $this->safeGet($entity, 'getPrix'),
            'site'            => $this->normalizeValue($this->safeGet($entity, 'getSite')),
            'constructeurIds' => $this->normalizeCollection($entity->getConstructeurs()),
        ];
    }
}
