<?php

namespace App\Addons\Services;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

/**
 * Addon Registrar Service
 * Registers enabled addons with Laravel
 */
class AddonRegistrar
{
    public function __construct(
        private AddonLoader $addonLoader
    ) {}

    /**
     * Register all enabled addons
     */
    public function registerAddons(): void
    {
        $enabledAddons = $this->addonLoader->getEnabledAddons();

        foreach ($enabledAddons as $slug) {
            $this->registerAddon($slug);
        }
    }

    /**
     * Register a single addon
     */
    private function registerAddon(string $slug): void
    {
        try {
            $addon = $this->addonLoader->loadAddon($slug);

            if (! $addon) {
                Log::warning("Cannot register addon {$slug}: not found");

                return;
            }

            $providerClass = $this->addonLoader->loadServiceProvider($slug, $addon);

            if (! $providerClass) {
                Log::warning("Cannot register addon {$slug}: provider not found");

                return;
            }

            // Register service provider
            if (class_exists($providerClass) && is_subclass_of($providerClass, ServiceProvider::class)) {
                // Get the application instance
                $app = app();

                // Register the provider
                $app->register($providerClass);

                // Set manifest if provider supports it
                if (method_exists($providerClass, 'setManifest')) {
                    $provider = $app->make($providerClass);
                    $provider->setManifest($addon);
                }
            }
        } catch (\Exception $e) {
            // Don't break the application if addon fails to load
            Log::error("Error registering addon {$slug}: ".$e->getMessage());
        }
    }

    /**
     * Load addon routes
     */
    public function loadAddonRoutes(): void
    {
        $enabledAddons = $this->addonLoader->getEnabledAddons();

        foreach ($enabledAddons as $slug) {
            $routesPath = $this->addonLoader->getRoutesPath($slug);

            if ($routesPath && file_exists($routesPath)) {
                try {
                    require $routesPath;
                } catch (\Exception $e) {
                    Log::error("Error loading routes for addon {$slug}: ".$e->getMessage());
                }
            }
        }
    }
}
