<?php

namespace App\Traits\Basics;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Exception;

trait HandlesJsonExceptions
{
    protected function handleJsonException(Exception $e): ?JsonResponse
    {
        if ($e instanceof ModelNotFoundException) {
            return response()->json([
                'error' => __('Resource with the given ID was not found.'),
                'log'   => $e->getMessage(),
            ], 404);
        }

        if ($e instanceof QueryException) {
            if ($e->getCode() == '23000') {
                return response()->json([
                    'error' => __('Cannot delete this record because it is linked with other records.'),
                ], 409);
            }

            return response()->json([
                'error' => __('A database error occurred.'),
                'log'   => $e->getMessage(),
            ], 500);
        }

        return response()->json([
            'error' => __('An unexpected error occurred.'),
            'log'   => $e->getMessage(),
        ], 500);
    }
}
