<?php

use App\Http\Middleware\EnsureCollabsWorkspace;
use App\Http\Middleware\EnsureSuperAdmin;
use App\Http\Middleware\HandleInstallationMode;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Support\Facades\Route;

$basePath = dirname(__DIR__);
if (! is_file($basePath.'/.env') && is_file($basePath.'/.env.example')) {
    @copy($basePath.'/.env.example', $basePath.'/.env');
}

return Application::configure(basePath: $basePath)
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        // --- Web installer (safe to remove after deploy; see docs/CPANEL.md) ---
        then: function (): void {
            if (app()->runningUnitTests()) {
                return;
            }
            if (! is_file(storage_path('app/.installed'))) {
                Route::middleware('web')
                    ->group(base_path('routes/install.php'));
            }
        },
        // --- end web installer ---
    )
    ->withSchedule(function (Schedule $schedule): void {
        $schedule->command('collabs:push-reminders')->dailyAt('09:00');
    })
    ->withMiddleware(function (Middleware $middleware): void {
        // Web installer gate (remove with installer files; see docs/CPANEL.md)
        $middleware->prependToGroup('web', HandleInstallationMode::class);

        $middleware->alias([
            'collabs.workspace' => EnsureCollabsWorkspace::class,
            'superadmin' => EnsureSuperAdmin::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
