<?php

declare(strict_types=1);

namespace App\Controller;

use App\Entity\CustomField;
use App\Entity\CustomFieldValue;
use App\Entity\Machine;
use App\Repository\CustomFieldValueRepository;
use App\Repository\MachineRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/api/machines')]
class MachineCustomFieldsController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly MachineRepository $machineRepository,
        private readonly CustomFieldValueRepository $customFieldValueRepository,
    ) {}

    #[Route('/{id}/add-custom-fields', name: 'machine_add_custom_fields', methods: ['POST'])]
    public function addMissingCustomFields(string $id): JsonResponse
    {
        $this->denyAccessUnlessGranted('ROLE_GESTIONNAIRE');

        $machine = $this->machineRepository->find($id);
        if (!$machine instanceof Machine) {
            return $this->json(['success' => false, 'error' => 'Machine not found.'], 404);
        }

        foreach ($machine->getCustomFields() as $customField) {
            if (!$customField instanceof CustomField) {
                continue;
            }
            $existing = $this->customFieldValueRepository->findOneBy([
                'machine'     => $machine,
                'customField' => $customField,
            ]);
            if ($existing instanceof CustomFieldValue) {
                continue;
            }

            $value = new CustomFieldValue();
            $value->setMachine($machine);
            $value->setCustomField($customField);
            $value->setValue($customField->getDefaultValue() ?? '');
            $this->entityManager->persist($value);
        }

        $this->entityManager->flush();

        $values = $this->customFieldValueRepository->findBy(['machine' => $machine]);

        return $this->json([
            'success'           => true,
            'machineId'         => $machine->getId(),
            'customFieldValues' => array_map(
                static fn (CustomFieldValue $value) => [
                    'id'            => $value->getId(),
                    'value'         => $value->getValue(),
                    'customFieldId' => $value->getCustomField()->getId(),
                ],
                $values
            ),
        ]);
    }
}
