<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('plans', function (Blueprint $table): void {
            $table->json('provisioning_config')->nullable()->after('features');
        });

        // Migrate existing virtfusion config from features to provisioning_config
        DB::table('plans')->whereNotNull('features')->get()->each(function ($plan) {
            $features = json_decode($plan->features, true) ?? [];
            $provisioningConfig = [];

            if (isset($features['virtfusion_package_id'])) {
                $provisioningConfig['package_id'] = (int) $features['virtfusion_package_id'];
                unset($features['virtfusion_package_id']);
            }

            if (isset($features['virtfusion_hypervisor_id'])) {
                $provisioningConfig['hypervisor_id'] = (int) $features['virtfusion_hypervisor_id'];
                unset($features['virtfusion_hypervisor_id']);
            }

            if (! empty($provisioningConfig)) {
                DB::table('plans')->where('id', $plan->id)->update([
                    'provisioning_config' => json_encode($provisioningConfig),
                    'features' => json_encode($features),
                ]);
            }
        });
    }

    public function down(): void
    {
        // Move provisioning_config back into features before dropping
        DB::table('plans')->whereNotNull('provisioning_config')->get()->each(function ($plan) {
            $features = json_decode($plan->features, true) ?? [];
            $config = json_decode($plan->provisioning_config, true) ?? [];

            // Intentionally lossy: up() casts string→int, down() casts back to string.
            // Original values were stored as strings in the features JSON.
            if (isset($config['package_id'])) {
                $features['virtfusion_package_id'] = (string) $config['package_id'];
            }

            if (isset($config['hypervisor_id'])) {
                $features['virtfusion_hypervisor_id'] = (string) $config['hypervisor_id'];
            }

            DB::table('plans')->where('id', $plan->id)->update([
                'features' => json_encode($features),
            ]);
        });

        Schema::table('plans', function (Blueprint $table): void {
            $table->dropColumn('provisioning_config');
        });
    }
};
