<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Throwable;

abstract class Controller
{
    public function successResponse($payload = null, ?string $message = null, int $code = 200): JsonResponse
    {
        return response()->json(data: ['payload' => $payload, 'message' => $message], status: $code);
    }

    public function errorResponse(
        ?string    $message   = null,
        int        $code      = 404,
        ?Throwable $exception = null,
    ): JsonResponse {
        if ($code >= 500) {
            $route = Route::current();

            Log::withContext([
                'route'      => $route?->uri(),
                'route_name' => $route?->getName(),
                'controller' => $route?->getActionName(),
                'method'     => request()->method(),
            ]);

            if ($exception) {
                report($exception);
            } else {
                Log::error('Resposta de erro interno retornada pela API.', [
                    'message' => $message,
                    'code'    => $code,
                ]);
            }
        }

        return response()->json(data: ['message' => $message], status: $code);
    }
}
