<?php

declare(strict_types=1);

namespace App\EventSubscriber;

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

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

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

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

    protected function getOwnerFromCustomFieldValue(CustomFieldValue $cfv): ?object
    {
        return $cfv->getPiece();
    }

    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'),
            'typePiece'       => $this->normalizeValue($this->safeGet($entity, 'getTypePiece')),
            'product'         => $this->normalizeValue($this->safeGet($entity, 'getProduct')),
            'productIds'      => $this->safeGet($entity, 'getProductIds') ?? [],
            'constructeurIds' => $this->normalizeCollection($entity->getConstructeurs()),
        ];
    }
}
