<?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', 'ticket_id')) {
            Schema::table('activities', function (Blueprint $table) {
                $table->foreignId('ticket_id')->nullable()->index()->after('deal_id');
            });
        }

        DB::table('activities')
            ->whereNotNull('legacy_type')
            ->whereNotNull('legacy_id')
            ->whereNull('ticket_id')
            ->orderBy('id')
            ->chunkById(200, function ($activities) {
                foreach ($activities as $activity) {
                    $table = match ($activity->legacy_type) {
                        'call' => 'calls',
                        'task' => 'tasks',
                        'event' => 'events',
                        default => null,
                    };
                    if (! $table) {
                        continue;
                    }
                    $ticketId = DB::table($table)->where('id', $activity->legacy_id)->value('ticket_id');
                    if ($ticketId) {
                        DB::table('activities')->where('id', $activity->id)->update(['ticket_id' => $ticketId]);
                    }
                }
            });
    }

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