<?php

namespace App\Handlers\Forms;

use App\Entity\Properties\Bien;
use App\Managers\ManagersInterface;
use Symfony\Component\Form\FormInterface;
use App\Interfaces\NotificationsInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

class BiensHandle
{
    public function __construct(
        private NotificationsInterface $notifications,
        private ManagersInterface $managers
    ) {}

    public function handleBienForm(FormInterface $form): JsonResponse
    {
        if ($form->isValid()) {
            return $this->handleValidForm($form);
        } else {
            return $this->handleInvalidForm($form);
        }
    }

    private function handleValidForm(FormInterface $form): JsonResponse
    {
        /** @var Bien $bien */
        $bien = $form->getData();
        if ($bien->getId()) {

            $this->managers->setEntity($bien, 'edit');
            $this->notifications->save(
                "Modification du bien #{$bien->getName()}",
                "Modification",
                $bien,
                "pencil5",
                "orange",
                $bien->getCompanyId()
            );
            $msg = 'Bien modifié avec succès.';
        } else {
            $this->managers->setEntity($bien, 'new');
            $this->notifications->save(
                "Nouveau bien #{$bien->getName()}",
                "Création",
                $bien,
                "plus",
                "green",
                $bien->getCompanyId()
            );
            $msg = 'Bien ajouté avec succès.';
        }

        return new JsonResponse([
            'code' => Bien::BIEN_ADD_SUCCESSFULLY,
            'msg' => $msg,
        ]);
    }

    private function handleInvalidForm(FormInterface $form): JsonResponse
    {

        return new JsonResponse([
            'code' => Bien::BIEN_INVALID_FORM,
            'errors' => $this->getErrorsMessages($form)
        ]);
    }

    private function getErrorsMessages(FormInterface $form): array
    {
        $errors = [];

        foreach ($form->getErrors() as $error) {
            $errors[] = $error->getMessage();
        }

        foreach ($form->all() as $child) {
            if (!$child->isValid()) {
                $errors[$child->getName()] = $this->getErrorsMessages($child);
            }
        }
        return $errors;
    }
}
