<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $this->replaceRule('nullable|image_or_base64', 'nullable|cropped_image_or_base64');
    }

    public function down(): void
    {
        $this->replaceRule('nullable|cropped_image_or_base64', 'nullable|image_or_base64');
    }

    private function replaceRule(string $from, string $to): void
    {
        DB::table('website_type_extras')
            ->where('codigo', 'heroConfig')
            ->orderBy('id')
            ->each(function (object $definition) use ($from, $to): void {
                $schema = json_decode((string) $definition->config_schema, true);

                if (! is_array($schema)) {
                    return;
                }

                $currentRule = $schema['request_rules']['background_image_id'] ?? null;

                if ($currentRule !== $from) {
                    return;
                }

                $schema['request_rules']['background_image_id'] = $to;

                DB::table('website_type_extras')
                    ->where('id', $definition->id)
                    ->update(['config_schema' => json_encode($schema)]);
            });
    }
};
