<?php

declare(strict_types=1);

namespace Flowaxy\Domain\Plugin\Services;

use Exception;
use Flowaxy\Support\Facades\Log;
use Throwable;

// Сервіс видалення плагіна
final class UninstallPluginService
{
    public function __construct(private readonly PluginRepositoryInterface $plugins)
    {
    }

    public function execute(string $slug, ?callable $beforeRemove = null): bool
    {
        if ($slug === '') {
            try {
                Log::Warning('Невалідний slug');
            } catch (Throwable $e) {
                // Ignore logging errors
            }
            return false;
        }

        try {
            Log::Debug('UninstallPluginService::execute: Starting uninstallation', [
                'slug' => $slug,
            ]);
        } catch (Throwable $e) {
            // Ignore logging errors
        }

        if ($beforeRemove !== null) {
            try {
                try {
                    Log::Debug('UninstallPluginService::execute: Calling beforeRemove callback', [
                        'slug' => $slug,
                    ]);
                } catch (Throwable $e) {
                    // Ignore logging errors
                }
                $beforeRemove($slug);
                try {
                    Log::Debug('UninstallPluginService::execute: beforeRemove callback executed successfully', [
                        'slug' => $slug,
                    ]);
                } catch (Throwable $e) {
                    // Ignore logging errors
                }
            } catch (Exception $e) {
                try {
                    Log::Error('Помилка виконання callback перед видаленням плагіна', ['slug' => $slug, 'exception' => $e]);
                } catch (Throwable $logError) {
                    // Ignore logging errors
                }
            }
        }

        $result = $this->plugins->uninstall($slug);

        if ($result) {
            try {
                Log::Info('UninstallPluginService::execute: Plugin uninstalled successfully', [
                    'slug' => $slug,
                ]);
            } catch (Throwable $e) {
                // Ignore logging errors
            }
        } else {
            try {
                Log::Error('Помилка видалення плагіна', ['slug' => $slug]);
            } catch (Throwable $e) {
                // Ignore logging errors
            }
        }

        return $result;
    }
}
