<?php

namespace App\Infrastructure\Traits;

use App\Infrastructure\Api\Response\AbstractResponse;
use ReflectionClass;
use Symfony\Component\HttpFoundation\JsonResponse;

trait ApiHelperTrait
{
    public function createJsonResponse(array $body, string $message = 'OK', int $code = 200): JsonResponse
    {
        return new JsonResponse([
            'message' => $message,
            'body' => $body,
        ], $code);
    }

    public function createPaginateJsonResponse(array $items, int $limit, int $totalCount): JsonResponse
    {
        return $this->createJsonResponse(
            [
                'items' => $items,
                'pages' => ceil($totalCount / $limit),
                'totalCount' => $totalCount,
            ]
        );
    }

    public function createJsonResponseFromObject(AbstractResponse $body, string $message = 'OK', int $code = 200): JsonResponse
    {
        return new JsonResponse([
            'message' => $message,
            'body' => $this->toArray($body),
        ], $code);
    }

    private function toArray(AbstractResponse $body): array
    {
        $reflect = new ReflectionClass($body);
        $props = $reflect->getProperties();
        $array = [];
        foreach ($props as $prop) {
            $prop->setAccessible(true);
            $array[$prop->getName()] = $prop->getValue($body);
            $prop->setAccessible(false);
        }

        return $array;
    }
}
