<?php

use App\Http\Middleware\BillerMiddleware;
use App\Http\Middleware\ClientPortalMiddleware;
use App\Http\Middleware\KitchenMiddleware;
use App\Http\Middleware\SuperAdminMiddleware;
use App\Http\Middleware\WaiterMiddleware;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        then: function () {
            Route::middleware('web')->prefix('super-admin')
                ->group(base_path('routes/super-admin.php'));

            Route::middleware('web')->prefix('portal')
                ->group(base_path('routes/portal.php'));

            Route::middleware('web')->prefix('biller')
                ->group(base_path('routes/biller.php'));

            Route::middleware('web')->prefix('kitchen')
                ->group(base_path('routes/kitchen.php'));

            Route::middleware('web')->prefix('waiter')
                ->group(base_path('routes/waiter.php'));
        }
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->redirectGuestsTo(function (Request $request) {
            if ($request->is('super-admin') || $request->is('super-admin/*')) {
                return route('super-admin.login');
            }
            if ($request->is('portal') || $request->is('portal/*')) {
                return route('portal.login');
            }
            if ($request->is('biller') || $request->is('biller/*')) {
                return route('biller.login');
            }
            if ($request->is('kitchen') || $request->is('kitchen/*')) {
                return route('kitchen.login');
            }
            if ($request->is('waiter') || $request->is('waiter/*')) {
                return route('waiter.login');
            }

            // Fallback
            return route('login');
        });

        $middleware->alias([
            'super-admin' => SuperAdminMiddleware::class,
            'client.portal' => ClientPortalMiddleware::class,
            'biller' => BillerMiddleware::class,
            'kitchen' => KitchenMiddleware::class,
            'waiter' => WaiterMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
