<?php

declare(strict_types=1);

namespace App\Service;

use App\Entity\Composant;
use App\Entity\CustomFieldValue;
use App\Entity\Piece;
use Doctrine\ORM\EntityNotFoundException;

class ReferenceAutoGenerator
{
    public function generate(Composant|Piece $entity): ?string
    {
        $modelType = $entity instanceof Piece
            ? $entity->getTypePiece()
            : $entity->getTypeComposant();

        if (!$modelType || !$modelType->getReferenceFormula()) {
            return null;
        }

        $valueMap = $this->buildValueMap($entity);

        $requiredFields = $modelType->getRequiredFieldsForReference();

        if ($requiredFields) {
            foreach ($requiredFields as $fieldName) {
                if (!isset($valueMap[$fieldName]) || '' === $valueMap[$fieldName]) {
                    return null;
                }
            }
        }

        return preg_replace_callback('/\{([^}]+)\}/u', static function (array $matches) use ($valueMap): string {
            return $valueMap[$matches[1]] ?? '';
        }, $modelType->getReferenceFormula());
    }

    /**
     * Build a map of fieldName → normalized value from the entity's CustomFieldValues.
     *
     * @return array<string, string>
     */
    private function buildValueMap(Composant|Piece $entity): array
    {
        $map = [];

        /** @var CustomFieldValue $cfv */
        foreach ($entity->getCustomFieldValues() as $cfv) {
            try {
                $name = $cfv->getCustomField()->getName();
            } catch (EntityNotFoundException) {
                continue;
            }
            $map[$name] = mb_strtoupper(trim($cfv->getValue()));
        }

        return $map;
    }
}
