<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('inventory_items') || ! Schema::hasTable('inventory_sync_runs') || ! Schema::hasTable('operation_runs')) {
            return;
        }

        if (! Schema::hasColumn('inventory_items', 'last_seen_run_id') || ! Schema::hasColumn('inventory_items', 'last_seen_operation_run_id')) {
            return;
        }

        DB::table('inventory_items')
            ->select(['id', 'last_seen_run_id', 'last_seen_operation_run_id'])
            ->orderBy('id')
            ->chunkById(500, function (Collection $rows): void {
                $legacyRunIds = $rows
                    ->pluck('last_seen_run_id')
                    ->filter(fn (mixed $id): bool => is_numeric($id))
                    ->map(fn (mixed $id): int => (int) $id)
                    ->unique()
                    ->values();

                if ($legacyRunIds->isEmpty()) {
                    return;
                }

                $operationRunIdByLegacyRunId = DB::table('inventory_sync_runs')
                    ->whereIn('id', $legacyRunIds->all())
                    ->whereNotNull('operation_run_id')
                    ->pluck('operation_run_id', 'id')
                    ->map(fn (mixed $id): int => (int) $id);

                if ($operationRunIdByLegacyRunId->isEmpty()) {
                    return;
                }

                $existingOperationRunIds = DB::table('operation_runs')
                    ->whereIn('id', $operationRunIdByLegacyRunId->values()->unique()->all())
                    ->pluck('id')
                    ->mapWithKeys(fn (mixed $id): array => [(int) $id => true]);

                foreach ($rows as $row) {
                    if ($row->last_seen_operation_run_id !== null || ! is_numeric($row->last_seen_run_id)) {
                        continue;
                    }

                    $candidate = $operationRunIdByLegacyRunId->get((int) $row->last_seen_run_id);

                    if (! is_numeric($candidate) || ! $existingOperationRunIds->has((int) $candidate)) {
                        continue;
                    }

                    DB::table('inventory_items')
                        ->where('id', (int) $row->id)
                        ->update(['last_seen_operation_run_id' => (int) $candidate]);
                }
            });
    }

    public function down(): void
    {
        if (! Schema::hasTable('inventory_items') || ! Schema::hasColumn('inventory_items', 'last_seen_operation_run_id')) {
            return;
        }

        DB::table('inventory_items')->update(['last_seen_operation_run_id' => null]);
    }
};
