<?php
/**
 * Synchronizes WordPress plugin lifecycle with integration registry status.
 *
 * @package FleekDash\Integration
 */

namespace FleekDash\Integration;

use FleekDash\Core\PluginHelper;

defined('ABSPATH') || exit;

final class PluginLifecycleSync
{
    /**
     * @return array{success: bool, error?: string}
     */
    public static function syncWordPressPluginForIntegration(string $integration_id, bool $active): array
    {
        $result = ['success' => true];
        $integration = Registry::get($integration_id);
        $plugin_file = (string) ($integration['plugin_file'] ?? '');
        $should_sync = self::isExternalPluginFile($plugin_file);

        if ($should_sync) {
            self::ensurePluginApiLoaded();
            $status = self::applyPluginStatus($plugin_file, $active);
            if (!($status['success'] ?? false)) {
                $result = [
                    'success' => false,
                    'error' => (string) ($status['error'] ?? 'Plugin lifecycle synchronization failed'),
                ];
            }
        }

        return $result;
    }

    public static function syncRegistryFromPluginLifecycle(string $plugin_file, bool $active): void
    {
        global $wpdb;

        $plugin_file = \sanitize_text_field($plugin_file);
        if (!self::isExternalPluginFile($plugin_file)) {
            return;
        }

        $table = $wpdb->prefix . 'fleekdash_integration_registry';
        $integration_id = (string) $wpdb->get_var(
            $wpdb->prepare(
                "SELECT integration_id FROM `{$table}` WHERE plugin_file = %s LIMIT 1",
                $plugin_file
            )
        );

        if ($integration_id === '') {
            return;
        }

        if ($active) {
            Registry::activate($integration_id);
        } else {
            Registry::deactivate($integration_id);
        }
    }

    /**
     * @return array{success: bool, error?: string}
     */
    private static function applyPluginStatus(string $plugin_file, bool $active): array
    {
        $plugin_path = \WP_PLUGIN_DIR . '/' . $plugin_file;

        if (!\file_exists($plugin_path) && $active) {
            $outcome = ['success' => false, 'error' => 'Linked plugin file not found: ' . $plugin_file];
        } elseif (\function_exists('is_plugin_active')) {
            if ($active) {
                $outcome = self::activatePluginIfNeeded($plugin_file);
            } else {
                $outcome = self::deactivatePluginIfNeeded($plugin_file);
            }
        } else {
            $outcome = ['success' => false, 'error' => 'WordPress plugin API is unavailable'];
        }

        return $outcome;
    }

    /**
     * @return array{success: bool, error?: string}
     */
    private static function activatePluginIfNeeded(string $plugin_file): array
    {
        $outcome = ['success' => true];

        if (!\is_plugin_active($plugin_file)) {
            $activation_result = \activate_plugin($plugin_file);
            if (\is_wp_error($activation_result)) {
                $outcome = ['success' => false, 'error' => $activation_result->get_error_message()];
            }
        }

        return $outcome;
    }

    /**
     * @return array{success: bool, error?: string}
     */
    private static function deactivatePluginIfNeeded(string $plugin_file): array
    {
        $outcome = ['success' => true];

        if (\is_plugin_active($plugin_file)) {
            \deactivate_plugins($plugin_file, false, false);
            if (\is_plugin_active($plugin_file)) {
                $outcome = ['success' => false, 'error' => 'WordPress plugin deactivation failed: ' . $plugin_file];
            }
        }

        return $outcome;
    }

    private static function isExternalPluginFile(string $plugin_file): bool
    {
        return $plugin_file !== '' && strpos($plugin_file, 'fleekdash-internal/') !== 0;
    }

    private static function ensurePluginApiLoaded(): void
    {
        if (\function_exists('is_plugin_active') && \function_exists('activate_plugin')) {
            return;
        }

        if (\class_exists(PluginHelper::class)) {
            PluginHelper::ensurePluginApiLoaded();
            return;
        }

        if (!\function_exists('is_plugin_active') || !\function_exists('activate_plugin')) {
            require_once \ABSPATH . 'wp-admin/includes/plugin.php';
        }
    }
}
