<?php

use App\Domains\Purchase\Models\Purchase;
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('value_changes', function (Blueprint $table): void {
            $table->string('tenant_code')->nullable()->after('id');
            $table->foreign('tenant_code')
                ->references('codigo')
                ->on('tenants')
                ->cascadeOnUpdate()
                ->nullOnDelete();
            $table->index(['tenant_code', 'changed_at']);
        });

        DB::table('value_changes')
            ->where('trackable_type', (new Purchase)->getMorphClass())
            ->whereNull('tenant_code')
            ->orderBy('id')
            ->chunkById(500, function ($changes): void {
                foreach ($changes as $change) {
                    $tenantCode = DB::table('compras')
                        ->where('id', $change->trackable_id)
                        ->value('tenant_codigo');

                    if ($tenantCode !== null) {
                        DB::table('value_changes')
                            ->where('id', $change->id)
                            ->update(['tenant_code' => $tenantCode]);
                    }
                }
            });
    }

    public function down(): void
    {
        Schema::table('value_changes', function (Blueprint $table): void {
            $table->dropForeign(['tenant_code']);
            $table->dropIndex(['tenant_code', 'changed_at']);
            $table->dropColumn('tenant_code');
        });
    }
};
