<?php

namespace App\Shared\Controller;

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

abstract class BaseController extends AbstractController
{
    protected function success(mixed $data, int $status = 200, array $meta = []): JsonResponse
    {
        $response = ['success' => true, 'data' => $data];
        if (!empty($meta)) {
            $response['meta'] = $meta;
        }
        return new JsonResponse($response, $status);
    }

    protected function paginated(mixed $data, int $total, int $page, int $limit): JsonResponse
    {
        return $this->success($data, 200, [
            'totalRecords' => $total,
            'totalPages'   => (int) ceil($total / max($limit, 1)),
            'currentPage'  => $page,
        ]);
    }

    protected function error(string $code, string $message, int $status = 400, ?string $field = null): JsonResponse
    {
        $err = ['code' => $code, 'message' => $message];
        if ($field !== null) {
            $err['field'] = $field;
        }
        return new JsonResponse(['success' => false, 'data' => null, 'errors' => [$err]], $status);
    }

    protected function validationError(array $violations): JsonResponse
    {
        $errors = [];
        foreach ($violations as $field => $messages) {
            foreach ((array) $messages as $message) {
                $errors[] = [
                    'code'    => 'ERR_VALIDATION_001',
                    'field'   => $field,
                    'message' => $message,
                ];
            }
        }
        return new JsonResponse(['success' => false, 'data' => null, 'errors' => $errors], 422);
    }
}
