<?php

use App\Http\Middleware\EnsureCompanyIsActive;
use App\Http\Middleware\EnsureUserIsMaster;
use App\Http\Middleware\PrepararInstalador;
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\PreventRequestForgery;
use Illuminate\Http\Request;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\Support\Facades\Route;
use Illuminate\View\Middleware\ShareErrorsFromSession;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        then: function () {
            // Fora do grupo "web" de propósito: o instalador tem pilha própria.
            Route::middleware('instalador')->group(base_path('routes/instalador.php'));
        },
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'master' => EnsureUserIsMaster::class,
            'empresa.ativa' => EnsureCompanyIsActive::class,
        ]);

        $middleware->redirectGuestsTo(fn () => route('login'));

        /*
         * Pilha própria do instalador web.
         *
         * Não usa o grupo "web" porque este guarda sessão e cache em banco —
         * e durante a instalação o banco ainda está vazio. PrepararInstalador
         * vem primeiro justamente para trocar esses drivers para arquivo antes
         * de a sessão iniciar.
         */
        $middleware->group('instalador', [
            PrepararInstalador::class,
            EncryptCookies::class,
            AddQueuedCookiesToResponse::class,
            StartSession::class,
            ShareErrorsFromSession::class,
            PreventRequestForgery::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->shouldRenderJsonWhen(
            fn (Request $request) => $request->is('api/*'),
        );
    })->create();
