<?php
declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../src/Config/redbean.php';

use DI\ContainerBuilder;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;
use Twig\Loader\FilesystemLoader;
use RedBeanPHP\R;          // <-- import de la façade RedBean

// -------------------------------------------------
// Conteneur DI
// -------------------------------------------------
$containerBuilder = new ContainerBuilder();

$containerBuilder->addDefinitions([

    // Twig
    Twig::class => function () {
        $loader = new FilesystemLoader(__DIR__ . '/../views');
        return new Twig($loader, ['cache' => false]); // désactivé en dev
    },

    // RedBean – service DB
    'db' => function () {
        $dbPath = __DIR__ . '/../database/app.sqlite';
        initRedBean($dbPath);                 // crée le fichier + connexion
        return R::getDatabaseAdapter();      // valeur retournée (facultatif)
    },

    // …autres services
]);

$container = $containerBuilder->build();

/* -------------------------------------------------
   Initialise la connexion DB dès le bootstrap
   ------------------------------------------------- */
$container->get('db');   // déclenche initRedBean() avant le chargement des routes

AppFactory::setContainer($container);
$app = AppFactory::create();

$app->addErrorMiddleware(true, true, true);

$twig = $container->get(Twig::class);
$app->add(TwigMiddleware::create($app, $twig));

foreach (glob(__DIR__ . '/../src/Routes/*.routes.php') as $file) {
    (require $file)($app);
}

$app->run();
