<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        //
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // AJAX kérések esetén mindig JSON választ adunk, egyedi referencia kóddal
        $exceptions->renderable(function (Throwable $e, Request $request) {
            if ($request->ajax() || $request->wantsJson()) {
                // Validációs hibákat nem piszkáljuk – azokat a Laravel alapból kezeli
                if ($e instanceof ValidationException) {
                    return null;
                }

                // 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(['current_password', 'password', 'password_confirmation']),
                    '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);
            }

            return null;
        });
    })->create();
