<?php

declare(strict_types=1);

namespace App;

use DI\Container;
use Nyholm\Psr7\Factory\Psr17Factory;
use Slim\App;
use Slim\Factory\AppFactory;
use Symfony\Component\Dotenv\Dotenv;

final class Bootstrap
{
    public static function loadEnv(): void
    {
        $envFile = __DIR__ . '/../.env';
        if (is_readable($envFile)) {
            (new Dotenv())->usePutenv(true)->load($envFile);
        }
    }

    /**
     * @return array<string, mixed>
     */
    public static function envConfig(): array
    {
        return [
            'bot.token' => (string) getenv('BOT_TOKEN'),
            'bot.secret' => (string) getenv('MAX_BOT_API_SECRET'),
            'webhook.url' => (string) getenv('WEBHOOK_URL'),
            'webapp.url' => (string) getenv('WEB_APP_URL'),
            'debug.chat_id' => (int) (getenv('DEBUG_CHAT_ID') ?: 0),
            'selftest.chat_id' => (int) (getenv('SELFTEST_CHAT_ID') ?: 0),
            'app.env' => (string) (getenv('APP_ENV') ?: 'dev'),
            'app.debug' => filter_var(getenv('APP_DEBUG') ?: true, FILTER_VALIDATE_BOOLEAN),
        ];
    }

    public static function container(): Container
    {
        self::loadEnv();
        $definitions = require __DIR__ . '/../config/container.php';
        return new Container($definitions);
    }

    public static function app(): App
    {
        $container = self::container();
        $cfg = $container->get('config');
        AppFactory::setContainer($container);

        $app = AppFactory::create();
        $app->addErrorMiddleware(
            displayErrorDetails: (bool) ($cfg['app.debug'] ?? false),
            logErrors: true,
            logErrorDetails: true,
            logger: $container->get(\Psr\Log\LoggerInterface::class),
        );
        (require __DIR__ . '/../config/routes.php')($app);
        return $app;
    }
}
