<?php

use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull;
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Illuminate\Http\Request;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\Validation\ValidationException;
use Illuminate\View\Middleware\ShareErrorsFromSession;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__ . '/../routes/web.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->redirectGuestsTo(fn(Request $request) => null);

        $middleware->remove([
            EncryptCookies::class,
            AddQueuedCookiesToResponse::class,
            StartSession::class,
            ShareErrorsFromSession::class,
            ValidateCsrfToken::class,
            ConvertEmptyStringsToNull::class,
        ]);

        $middleware->removeFromGroup('web', [
            EncryptCookies::class,
            AddQueuedCookiesToResponse::class,
            StartSession::class,
            ShareErrorsFromSession::class,
            ValidateCsrfToken::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->renderable(function (ThrottleRequestsException $e, $request) {
            return response()->json(['message' => 'Too many requests'], 429);
        });
        $exceptions->render(function (Throwable $th, Request $request) {
            if ($th instanceof NotFoundHttpException) {
                return response('NotFound', 404);
            }
            if ($th instanceof ValidationException) {
                $message = $th->validator->errors()->first();
                return response()->json(['code' => 400, 'message' => $message]);
            }
            if ($th instanceof MethodNotAllowedHttpException) {
                return response()->json(['code' => 400, 'message' => 'MethodNotAllowed']);
            }

            info('===== application exception: ', [get_class($th)]);
            return response()->json(['message' => 'unknow exception'], 400);
        });

        // $exceptions->renderable(function(MiniappException $th, $request){});
        // $exceptions->render([AppException::class, 'render']);
        // $exceptions->dontReport(AppException::$dontReport);
    })->create();
