<?php

namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class Handle extends ExceptionHandler
{
    public function render($request, Throwable $exception): JsonResponse|Response
    {
        if (!$request->expectsJson()) {
            return parent::render($request, $exception);
        }

        $status = 500; // Default to internal server error
        $errorResponse = [
            'error' => 'Server Error',
            'message' => $exception->getMessage(),
        ];

        if ($exception instanceof ValidationException) {
            $status = 422;
            $errorResponse = [
                'error' => 'Validation Failed',
                'message' => 'The given data was invalid.',
                'errors' => $exception->errors(), // ✅ Ensure validation messages are inside "errors"
            ];
        } elseif ($exception instanceof NotFoundHttpException) {
            $status = 404;
            $errorResponse = [
                'error' => 'Resource Not Found',
                'message' => 'The requested resource was not found on this server.',
            ];
        } elseif ($exception instanceof QueryException) {
            $status = 500;
            $errorResponse = [
                'error' => 'Database Error',
                'message' => $exception->getMessage(),
            ];
        }

        return response()->json($errorResponse, $status);
    }


}
