<?php

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
    {
        if (! Schema::hasColumn('activities', 'account_id')) {
            Schema::table('activities', function (Blueprint $table) {
                $table->unsignedBigInteger('account_id')->nullable()->index()->after('project_id');
            });
        }

        DB::table('activities')
            ->whereNull('account_id')
            ->whereNotNull('deal_id')
            ->orderBy('id')
            ->chunkById(250, function ($activities) {
                $accountByDeal = DB::table('deals')
                    ->whereIn('id', $activities->pluck('deal_id')->filter()->unique())
                    ->pluck('account_id', 'id');

                foreach ($activities as $activity) {
                    $accountId = $accountByDeal[$activity->deal_id] ?? null;
                    if ($accountId) {
                        DB::table('activities')->where('id', $activity->id)->update(['account_id' => $accountId]);
                    }
                }
            });
    }

    public function down(): void
    {
        if (Schema::hasColumn('activities', 'account_id')) {
            Schema::table('activities', fn (Blueprint $table) => $table->dropColumn('account_id'));
        }
    }
};
