<?php

declare(strict_types=1);

namespace ShieldX\Core;

defined('ABSPATH') || exit;

use ShieldX\Database\SchemaInstaller;
use ShieldX\Security\LoginSecurity;
use ShieldX\Storage\FileStorage;
use ShieldX\Support\RuntimeCacheInvalidator;

final class Activator
{
    private const DEFERRED_TASKS_OPTION = 'shieldx_activation_deferred_tasks';

    public static function activate(): void
    {
        if (defined('SHIELDX_PLUGIN_DIR') && is_string(SHIELDX_PLUGIN_DIR)) {
            RuntimeCacheInvalidator::invalidateDirectory((string) SHIELDX_PLUGIN_DIR);
            RuntimeCacheInvalidator::clearPluginUpdateCache();
        }

        self::grantAdministratorCapability();

        $storage = FileStorage::fromWordPress();
        $storage->ensure();

        $installer = SchemaInstaller::fromWordPress();
        $installer->install();

        self::queueDeferredActivationTasks();
    }

    public static function runDeferredActivationTasks(): void
    {
        if (!function_exists('get_option') || (string) get_option(self::DEFERRED_TASKS_OPTION, '') !== '1') {
            return;
        }

        if (function_exists('delete_option')) {
            delete_option(self::DEFERRED_TASKS_OPTION);
        }

        AddonRegistry::fromWordPress()->dispatchLifecycle('shieldx_addon_activated');
        SchedulerBridge::refresh();
        self::scheduleCoreFallbacks();

        LoginSecurity::sendActivationRecoveryEmail();
    }

    private static function queueDeferredActivationTasks(): void
    {
        if (function_exists('update_option')) {
            update_option(self::DEFERRED_TASKS_OPTION, '1', false);
        }
    }

    public static function scheduleCoreFallbacks(bool $force = false): void
    {
        if ((!$force && SchedulerBridge::active()) || !function_exists('wp_next_scheduled') || !function_exists('wp_schedule_event')) {
            return;
        }

        if (!wp_next_scheduled('shieldx_hourly_maintenance')) {
            wp_schedule_event(time() + 300, 'hourly', 'shieldx_hourly_maintenance');
        }

        if (!wp_next_scheduled('shieldx_temp_cleanup')) {
            wp_schedule_event(time() + 900, 'daily', 'shieldx_temp_cleanup');
        }
    }

    public static function grantAdministratorCapability(): void
    {
        if (!defined('SHIELDX_MANAGE_CAPABILITY') || !function_exists('get_role')) {
            return;
        }

        $role = get_role('administrator');
        if (is_object($role) && method_exists($role, 'add_cap')) {
            $role->add_cap((string) SHIELDX_MANAGE_CAPABILITY);
        }
    }

}
