<?php

namespace App\Controller\Api;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class AbstractApiController extends AbstractController
{
    private function apiResponse(bool $success, array|NormalizableInterface $data): Response
    {
        if ($data instanceof NormalizableInterface) {
            $data = $data->normalize();
        }
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                if ($value instanceof NormalizableInterface) {
                    $data[$key] = $value->normalize();
                }
            }
        }

        return new JsonResponse([
            'success' => $success,
            'data' => $data,
        ]);
    }

    final protected function errorResponse(string $message): Response
    {
        return $this->apiResponse(false, ['message' => $message]);
    }

    final protected function successResponse(array|NormalizableInterface $data = []): Response
    {
        return $this->apiResponse(true, $data);
    }
}