<?php

namespace App\Addons\Services;

use App\Licensing\Services\Lixvalid;
use Exception;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;

/**
 * Addon Manager Service
 * Handles enabling/disabling addons and license checks
 */
class AddonManager
{
    public function __construct(
        private AddonLoader $addonLoader,
        private Lixvalid $lixvalid,
        private AddonSecurityValidator $securityValidator
    ) {}

    /**
     * Enable an addon
     */
    public function enable(string $slug): array
    {
        // Validate addon exists
        $addon = $this->addonLoader->loadAddon($slug);
        if (! $addon) {
            return [
                'success' => false,
                'message' => 'Addon not found',
            ];
        }

        // Check license if required
        if (isset($addon['requires_license']) && $addon['requires_license'] === true) {
            if (! $this->lixvalid->isValid()) {
                return [
                    'success' => false,
                    'message' => 'License is invalid. Cannot enable addon.',
                ];
            }
        }

        // Validate addon structure
        $validation = $this->addonLoader->validateAddon($slug);
        if (! $validation['valid']) {
            return [
                'success' => false,
                'message' => 'Addon validation failed: '.implode(', ', $validation['errors']),
            ];
        }

        // Security validation
        $addonPath = base_path('addons/'.$slug);
        if (is_dir($addonPath)) {
            $securityValidation = $this->securityValidator->validateAddon($addonPath);
            if (! $securityValidation['valid']) {
                Log::warning("Addon security validation failed for {$slug}: ".implode(', ', $securityValidation['errors']));

                return [
                    'success' => false,
                    'message' => 'Addon security validation failed: '.implode(', ', $securityValidation['errors']),
                ];
            }
        }

        // Add to enabled list
        $enabledAddons = $this->addonLoader->getEnabledAddons();

        if (! in_array($slug, $enabledAddons)) {
            $enabledAddons[] = $slug;
            $this->saveEnabledAddons($enabledAddons);

            // Clear config cache
            Artisan::call('config:clear');
        }

        return [
            'success' => true,
            'message' => 'Addon enabled successfully',
        ];
    }

    /**
     * Disable an addon
     */
    public function disable(string $slug): array
    {
        $enabledAddons = $this->addonLoader->getEnabledAddons();

        if (in_array($slug, $enabledAddons)) {
            $enabledAddons = array_values(array_filter($enabledAddons, fn ($item) => $item !== $slug));
            $this->saveEnabledAddons($enabledAddons);

            // Clear config cache
            Artisan::call('config:clear');
        }

        return [
            'success' => true,
            'message' => 'Addon disabled successfully',
        ];
    }

    /**
     * Save enabled addons list
     */
    private function saveEnabledAddons(array $enabledAddons): void
    {
        $configFile = storage_path('app/addons.json');
        $config = [
            'enabled' => $enabledAddons,
            'updated_at' => now()->toDateTimeString(),
        ];

        try {
            File::ensureDirectoryExists(dirname($configFile));
            file_put_contents($configFile, json_encode($config, JSON_PRETTY_PRINT));
        } catch (Exception $e) {
            Log::error('Error saving addons config: '.$e->getMessage());
            throw $e;
        }
    }

    /**
     * Check if addon can be enabled (license check)
     */
    public function canEnable(string $slug): bool
    {
        $addon = $this->addonLoader->loadAddon($slug);

        if (! $addon) {
            return false;
        }

        // If addon requires license, check it
        if (isset($addon['requires_license']) && $addon['requires_license'] === true) {
            return $this->lixvalid->isValid();
        }

        return true;
    }

    /**
     * Get addon status
     */
    public function getAddonStatus(string $slug): array
    {
        $addon = $this->addonLoader->loadAddon($slug);

        if (! $addon) {
            return [
                'exists' => false,
                'enabled' => false,
                'can_enable' => false,
            ];
        }

        $enabled = $this->addonLoader->isAddonEnabled($slug);
        $canEnable = $this->canEnable($slug);

        return [
            'exists' => true,
            'enabled' => $enabled,
            'can_enable' => $canEnable,
            'requires_license' => $addon['requires_license'] ?? false,
            'license_valid' => $this->lixvalid->isValid(),
        ];
    }
}
