<?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
    {
        Schema::create('deal_account', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('deal_id');
            $table->unsignedBigInteger('account_id');
            $table->timestamps();
            $table->unique(['deal_id', 'account_id']);
            $table->index('account_id');
        });

        DB::table('deals')
            ->whereNotNull('account_id')
            ->orderBy('id')
            ->chunkById(500, function ($deals) {
                foreach ($deals as $deal) {
                    DB::table('deal_account')->insertOrIgnore([
                        'deal_id' => $deal->id,
                        'account_id' => $deal->account_id,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            });
    }

    public function down(): void
    {
        Schema::dropIfExists('deal_account');
    }
};
