<?php

declare(strict_types=1);

namespace App\Framework\WebPush;

use App\Framework\Cache\Cache;
use App\Framework\DI\Container;
use App\Framework\DI\Initializer;
use App\Framework\WebPush\Console\VapidKeyCommands;
use App\Framework\WebPush\Console\WebPushCommands;
use App\Framework\WebPush\Repository\CacheSubscriptionRepository;
use App\Framework\WebPush\Repository\SubscriptionRepository;
use App\Framework\WebPush\Services\VapidKeyGenerator;
use App\Framework\WebPush\Services\WebPushService;
use App\Framework\WebPush\ValueObjects\VapidKeyPair;

/**
 * Initializes Web Push System components in DI Container.
 */
final readonly class WebPushInitializer
{
    public function __construct(
        private Container $container,
        private Cache $cache
    ) {
    }

    #[Initializer]
    public function initRepository(): SubscriptionRepository
    {
        return new CacheSubscriptionRepository($this->cache);
    }

    #[Initializer]
    public function initKeyGenerator(): VapidKeyGenerator
    {
        return new VapidKeyGenerator();
    }

    #[Initializer]
    public function initWebPushService(): ?WebPushService
    {
        // Try to load VAPID keys from environment
        $publicKey = $_ENV['VAPID_PUBLIC_KEY'] ?? null;
        $privateKey = $_ENV['VAPID_PRIVATE_KEY'] ?? null;
        $subject = $_ENV['VAPID_SUBJECT'] ?? 'mailto:admin@example.com';

        if ($publicKey !== null && $privateKey !== null) {
            $vapidKeys = new VapidKeyPair($publicKey, $privateKey);

            return new WebPushService($vapidKeys, $subject);
        }

        // Return null if keys not configured
        // This allows the system to bootstrap for key generation
        return null;
    }

    #[Initializer]
    public function initVapidKeyCommands(): VapidKeyCommands
    {
        return new VapidKeyCommands(
            $this->container->get(VapidKeyGenerator::class)
        );
    }

    #[Initializer]
    public function initWebPushCommands(): ?WebPushCommands
    {
        // Only register if WebPushService is configured
        $service = $this->container->get(WebPushService::class);

        if ($service === null) {
            return null;
        }

        return new WebPushCommands(
            $this->container->get(SubscriptionRepository::class),
            $service
        );
    }
}
