<?php

use App\Services\ThemeService;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
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',
    )
    ->withSchedule(function (\Illuminate\Console\Scheduling\Schedule $schedule): void {
        $schedule->command('gcms:check-update')->dailyAt('03:15');
    })
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->web(append: [
            \App\Http\Middleware\SetLocale::class,
        ]);
        $middleware->alias([
            'installed' => \App\Http\Middleware\CheckInstalled::class,
            'not.installed' => \App\Http\Middleware\RedirectIfNotInstalled::class,
            'admin' => \App\Http\Middleware\AdminMiddleware::class,
            'admin.only' => \App\Http\Middleware\EnsureAdminOnly::class,
            'admin.can_edit' => \App\Http\Middleware\EnsureCanEdit::class,
            'plugin.active' => \App\Http\Middleware\EnsurePluginActive::class,
            'newsletter.scheduler' => \App\Http\Middleware\ProcessScheduledNewsletters::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (NotFoundHttpException $e, $request) {
            if ($request->expectsJson()) {
                return null;
            }
            if (str_starts_with($request->path(), 'admin')) {
                return response()->view('errors.404-admin', [], 404);
            }
            try {
                return response(app(ThemeService::class)->render('404')->render(), 404);
            } catch (\Throwable $th) {
                return response()->view('errors.404-fallback', [], 404);
            }
        });
    })->create();
