<?php

namespace FleekDash\Integrations\Core;

defined('ABSPATH') || exit;

/**
 * Migration Manager for Integration System
 *
 * Handles migration from legacy to new system
 */
class MigrationManager
{
    private Container $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    /**
     * Run migrations
     */
    public function migrate(): void
    {
        $this->migrateLegacySettings();
        $this->clearLegacyCache();
        $this->updateVersion();
    }

    /**
     * Migrate legacy settings
     */
    private function migrateLegacySettings(): void
    {
        // Migrate settings from old format to new
        $legacyOpenAI = get_option('fleekdash_integration_openai', []);
        if (!empty($legacyOpenAI)) {
            update_option('fleekdash_openai_settings', $legacyOpenAI);
            delete_option('fleekdash_integration_openai');
        }
    }

    /**
     * Clear legacy cache
     */
    private function clearLegacyCache(): void
    {
        delete_transient('fleekdash_integrations_discovery');
    }

    /**
     * Update system version
     */
    private function updateVersion(): void
    {
        update_option('fleekdash_integrations_version', '2.0.0');
    }

    /**
     * Check if migration is needed
     */
    public function needsMigration(): bool
    {
        $version = get_option('fleekdash_integrations_version', '1.0.0');
        return version_compare($version, '2.0.0', '<');
    }

    /**
     * Get migration status
     */
    public function getStatus(): array
    {
        return [
            'needs_migration' => $this->needsMigration(),
            'current_version' => get_option('fleekdash_integrations_version', '1.0.0'),
            'target_version' => '2.0.0',
            'migrated_at' => get_option('fleekdash_integrations_migrated', 0)
        ];
    }
}
