<?php

$basePath = dirname(__DIR__);
$environmentPath = $basePath.'/.env';
if (! file_exists($basePath.'/storage/app/installed')) {
    if (! file_exists($environmentPath) && file_exists($basePath.'/.env.example')) {
        @copy($basePath.'/.env.example', $environmentPath);
    }
    if (is_writable($environmentPath)) {
        $environment = file_get_contents($environmentPath);
        if (is_string($environment) && preg_match('/^APP_KEY=\s*$/m', $environment)) {
            $key = 'base64:'.base64_encode(random_bytes(32));
            file_put_contents($environmentPath, preg_replace('/^APP_KEY=\s*$/m', 'APP_KEY='.$key, $environment), LOCK_EX);
        }
    }
}

use App\Http\Middleware\EnsureApplicationIsInstalled;
use App\Http\Middleware\EnsureApplicationIsNotInstalled;
use App\Http\Middleware\EnsureSubscriptionIsActive;
use App\Http\Middleware\EnsureTwoFactorChallengePassed;
use App\Http\Middleware\SetCurrentBusiness;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: $basePath)
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'business' => SetCurrentBusiness::class,
            'subscribed' => EnsureSubscriptionIsActive::class,
            'two-factor' => EnsureTwoFactorChallengePassed::class,
            'not-installed' => EnsureApplicationIsNotInstalled::class,
        ]);
        $middleware->prependToGroup('web', EnsureApplicationIsInstalled::class);
        $middleware->prependToGroup('api', EnsureApplicationIsInstalled::class);
        $middleware->appendToGroup('web', SetCurrentBusiness::class);
        $middleware->appendToGroup('api', SetCurrentBusiness::class);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
