<?php

declare(strict_types=1);

namespace CloudXM\SDK\Providers;

use CloudXM\SDK\Contracts\ConfigurationInterface;
use CloudXM\SDK\Support\HasLogger;

/**
 * Generic Update Service Provider
 *
 * A reusable provider that can be used by any CloudXM plugin to handle
 * plugin update checking functionality. Requires the plugin's configuration
 * and update service class name as parameters.
 */
class UpdateServiceProvider
{
    use HasLogger;

    public function __construct(
        private ConfigurationInterface $config,
        private string $updateServiceClass
    ) {}

    public function register(): void
    {
        // Register plugin update functionality
        $this->registerPluginUpdates();

        $this->log()->debug('sdk.update.initialized', [
            'service_class' => $this->updateServiceClass,
            'plugin_file' => $this->config->getPluginFilePath(),
            'sink' => 'internal'
        ]);
    }

    /**
     * Bind plugin update functionality
     */
    private function registerPluginUpdates(): void
    {
        // Instantiate the update service and initialize the update checker
        try {
            $updateService = new $this->updateServiceClass($this->config);
            $updateService->initUpdateChecker();
        } catch (\Throwable $e) {
            $this->log()->error('Failed to initialize update service', [
                'class' => $this->updateServiceClass,
                'error' => $e->getMessage()
            ]);
        }
    }
}