<?php

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

return new class extends Migration
{
    /**
     * @var array<string, string>
     */
    private array $upMap = [
        'inventory.sync' => 'inventory_sync',
        'directory_groups.sync' => 'entra_group_sync',
        'drift.generate' => 'drift_generate_findings',
        'backup_schedule.run_now' => 'backup_schedule_run',
        'backup_schedule.retry' => 'backup_schedule_run',
        'backup_schedule.scheduled' => 'backup_schedule_run',
    ];

    /**
     * @var array<string, string>
     */
    private array $downMap = [
        'inventory_sync' => 'inventory.sync',
        'entra_group_sync' => 'directory_groups.sync',
        'drift_generate_findings' => 'drift.generate',
        // Multiple legacy values are normalized into one canonical value.
        'backup_schedule_run' => 'backup_schedule.run_now',
    ];

    public function up(): void
    {
        if (! Schema::hasTable('operation_runs')) {
            return;
        }

        foreach ($this->upMap as $from => $to) {
            DB::table('operation_runs')
                ->where('type', $from)
                ->update(['type' => $to]);
        }
    }

    public function down(): void
    {
        if (! Schema::hasTable('operation_runs')) {
            return;
        }

        foreach ($this->downMap as $from => $to) {
            DB::table('operation_runs')
                ->where('type', $from)
                ->update(['type' => $to]);
        }
    }
};
