<?php

declare(strict_types=1);

namespace App\Framework\Console\Analytics;

use App\Framework\Console\Analytics\Middleware\AnalyticsCollectionMiddleware;
use App\Framework\Console\Analytics\Repository\CommandUsageRepository;
use App\Framework\Console\Analytics\Repository\DatabaseCommandUsageRepository;
use App\Framework\DI\Attributes\Initializer;
use App\Framework\DI\Container;
use App\Framework\Environment\Environment;
use App\Framework\Environment\EnvKey;

final readonly class AnalyticsInitializer
{
    public function __construct(
        private Environment $environment
    ) {
    }

    #[Initializer]
    public function initialize(Container $container): void
    {
        // Register repository
        $container->bind(
            CommandUsageRepository::class,
            DatabaseCommandUsageRepository::class
        );

        // Register analytics service
        $container->singleton(AnalyticsService::class, function (Container $container) {
            return new AnalyticsService(
                $container->get(CommandUsageRepository::class)
            );
        });

        // Register analytics collection middleware
        $container->singleton(AnalyticsCollectionMiddleware::class, function (Container $container) {
            $enabled = $this->environment->getBool(EnvKey::CONSOLE_ANALYTICS_ENABLED, true);

            return new AnalyticsCollectionMiddleware(
                repository: $container->get(CommandUsageRepository::class),
                enabled: $enabled
            );
        });
    }
}
