<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of exception types with their corresponding custom log levels.
     *
     * @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
     */
    protected $levels = [
        //
    ];

    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<\Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });

        // AJAX kérések esetén mindig JSON választ adunk, egyedi referencia kóddal
        $this->renderable(function (Throwable $e, $request) {
            if ($request->ajax() || $request->wantsJson()) {
                return $this->handleAjaxException($e, $request);
            }
        });
    }

    private function handleAjaxException(Throwable $e, $request): JsonResponse
    {
        // Validációs hibákat nem piszkáljuk – azokat a Laravel alapból kezeli
        if ($e instanceof \Illuminate\Validation\ValidationException) {
            return parent::render($request, $e);
        }

        // Egyedi referencia kód generálása
        $errorRef = 'ERR-' . now()->format('ymdHis') . '-' . strtoupper(Str::random(6));

        // Teljes technikai részlet a logba
        \Log::error("[$errorRef] Unhandled exception", [
            'error_ref'   => $errorRef,
            'message'     => $e->getMessage(),
            'exception'   => get_class($e),
            'file'        => $e->getFile(),
            'line'        => $e->getLine(),
            'url'         => $request->fullUrl(),
            'method'      => $request->method(),
            'user_id'     => auth()->id(),
            'input'       => $request->except($this->dontFlash),
            'trace'       => $e->getTraceAsString(),
        ]);

        $statusCode = method_exists($e, 'getStatusCode')
            ? $e->getStatusCode()
            : 500;

        return response()->json([
            'success' => false,
            'error_ref' => $errorRef,
            'message' => "Váratlan hiba történt. Hivatkozási kód: $errorRef",
        ], $statusCode);
    }
}
