<?php

declare(strict_types=1);

namespace App\Tests\Service;

use App\Enum\ModelCategory;
use App\Service\SkeletonStructureService;
use App\Tests\AbstractApiTestCase;

/**
 * @internal
 */
class SkeletonStructureServiceTest extends AbstractApiTestCase
{
    public function testRenameCustomFieldPropagatesToReferenceFormulaAndRequiredFields(): void
    {
        $mt = $this->createModelType('Roulement', 'ROUL-RENAME', ModelCategory::PIECE);
        $mt->setReferenceFormula('{material}-{size}');
        $mt->setRequiredFieldsForReference(['material', 'size']);

        $em = $this->getEntityManager();
        $em->flush();

        $cfMaterial = $this->createCustomField('material', 'text', typePiece: $mt, orderIndex: 0);
        $cfSize     = $this->createCustomField('size', 'text', typePiece: $mt, orderIndex: 1);

        /** @var SkeletonStructureService $service */
        $service = static::getContainer()->get(SkeletonStructureService::class);

        // Same fields, but `material` is renamed to `materiau` (matched by customFieldId)
        $service->updateSkeletonRequirements($mt, [
            'customFields' => [
                ['customFieldId' => $cfMaterial->getId(), 'name' => 'materiau', 'type' => 'text', 'orderIndex' => 0],
                ['customFieldId' => $cfSize->getId(), 'name' => 'size', 'type' => 'text', 'orderIndex' => 1],
            ],
        ]);

        $em->flush();
        $em->refresh($mt);
        $em->refresh($cfMaterial);

        self::assertSame('materiau', $cfMaterial->getName());
        self::assertSame('{materiau}-{size}', $mt->getReferenceFormula());
        self::assertSame(['materiau', 'size'], $mt->getRequiredFieldsForReference());
    }

    public function testRenameLeavesFormulaUnchangedWhenFieldNotInFormula(): void
    {
        $mt = $this->createModelType('Roulement2', 'ROUL-RENAME2', ModelCategory::PIECE);
        $mt->setReferenceFormula('{material}');
        $mt->setRequiredFieldsForReference(['material']);

        $em = $this->getEntityManager();
        $em->flush();

        $cfMaterial = $this->createCustomField('material', 'text', typePiece: $mt, orderIndex: 0);
        $cfUnused   = $this->createCustomField('unused', 'text', typePiece: $mt, orderIndex: 1);

        /** @var SkeletonStructureService $service */
        $service = static::getContainer()->get(SkeletonStructureService::class);

        $service->updateSkeletonRequirements($mt, [
            'customFields' => [
                ['customFieldId' => $cfMaterial->getId(), 'name' => 'material', 'type' => 'text', 'orderIndex' => 0],
                ['customFieldId' => $cfUnused->getId(), 'name' => 'renamed', 'type' => 'text', 'orderIndex' => 1],
            ],
        ]);

        $em->flush();
        $em->refresh($mt);

        self::assertSame('{material}', $mt->getReferenceFormula());
        self::assertSame(['material'], $mt->getRequiredFieldsForReference());
    }
}
