<?php

use App\Core\Http\Responses\ApiResponse;
use App\Http\Middleware\RecordDailyActiveUser;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->trustProxies(at: '*');

        $middleware->alias([
            'active' => \App\Http\Middleware\EnsureUserIsActive::class,
            'admin' => \App\Http\Middleware\EnsureUserIsAdmin::class,
            'web' => \App\Http\Middleware\EnsureWebUser::class,
            'api.token' => \App\Http\Middleware\EnsureApiToken::class,
        ]);

        $middleware->redirectGuestsTo(function (Request $request) {
            if ($request->is('admin', 'admin/*')) {
                return route('admin.login');
            }

            return route('web.login');
        });

        $middleware->redirectUsersTo(function (Request $request) {
            if ($request->is('admin', 'admin/*')) {
                return route('admin.dashboard');
            }

            return route('web.dashboard');
        });

        $middleware->appendToGroup('api', [
            RecordDailyActiveUser::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->shouldRenderJsonWhen(function (Request $request, \Throwable $e) {
            return $request->is('api/*');
        });

        $exceptions->render(function (ValidationException $e, Request $request) {
            if (! $request->is('api/*')) {
                return null;
            }

            return ApiResponse::errorResponse(
                'تحقق من البيانات المدخلة.',
                array_merge(['code' => 'validation_failed'], ['errors' => $e->errors()]),
                $e->status
            );
        });

        $exceptions->render(function (AuthenticationException $e, Request $request) {
            if (! $request->is('api/*')) {
                return null;
            }

            return ApiResponse::errorResponse('يرجى تسجيل الدخول.', ['code' => 'unauthenticated'], 401);
        });

        $exceptions->render(function (NotFoundHttpException $e, Request $request) {
            if (! $request->is('api/*')) {
                return null;
            }

            return ApiResponse::errorResponse('المورد غير موجود.', ['code' => 'not_found'], 404);
        });

        $exceptions->render(function (\Throwable $e, Request $request) {
            if (! $request->is('api/*')) {
                return null;
            }

            if ($e instanceof ValidationException
                || $e instanceof AuthenticationException
                || $e instanceof NotFoundHttpException) {
                return null;
            }

            if ($e instanceof HttpExceptionInterface) {
                $status = $e->getStatusCode();
                if ($status === 429) {
                    return ApiResponse::errorResponse(
                        'عدد الطلبات مرتفع. حاول بعد قليل.',
                        ['code' => 'too_many_requests'],
                        429
                    );
                }

                $code = match ($status) {
                    403 => 'forbidden',
                    401 => 'unauthorized',
                    default => 'http_error',
                };

                return ApiResponse::errorResponse(
                    $e->getMessage() ?: 'تعذر تنفيذ الطلب.',
                    ['code' => $code],
                    $status
                );
            }

            if (config('app.debug')) {
                return ApiResponse::errorResponse($e->getMessage(), [
                    'code' => 'debug_exception',
                    'exception' => $e::class,
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                ], 500);
            }

            Log::error('api.unhandled_exception', [
                'message' => $e->getMessage(),
                'exception' => $e::class,
                'url' => $request->fullUrl(),
                'user_id' => $request->user()?->id,
            ]);

            return ApiResponse::errorResponse(
                'حدث خطأ في الخادم. تم تسجيله للمراجعة.',
                ['code' => 'server_error'],
                500
            );
        });
    })->create();
