<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /migrations/031_encrypt_api_keys.php
// Description: Encrypt any plaintext amai_api_key_* values in wp_options via KeyVault - NUCLEAR+++
// Last Edited: 2026-05-11
// ==================================================

namespace AutoMarketerAI\Migrations;

defined('ABSPATH') || exit;

final class Migration_031_EncryptApiKeys
{
    public function up(): void
    {
        global $wpdb;

        $rows = $wpdb->get_results(
            "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE 'amai_api_key_%'",
            ARRAY_A
        );

        if (empty($rows)) {
            return;
        }

        foreach ($rows as $row) {
            $value = (string) $row['option_value'];
            if ($value === '') {
                continue;
            }
            // Skip values that are already encrypted (base64 with aes- prefix pattern)
            if (str_starts_with($value, 'amai_enc:')) {
                continue;
            }
            update_option($row['option_name'], \AutoMarketerAI\KeyVault::encrypt($value));
        }
    }
}