<?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::table('import_mappings', function (Blueprint $table) {
            if (! Schema::hasColumn('import_mappings', 'entity')) {
                $table->string('entity', 64)->nullable()->after('import_id');
            }
            $table->index(['import_id', 'entity']);
        });

        // Backfill entity from target_field's first segment where possible
        DB::table('import_mappings')->orderBy('id')->chunkById(1000, function ($rows) {
            foreach ($rows as $row) {
                if (! empty($row->entity)) {
                    continue;
                }
                $entity = null;
                if (! empty($row->target_field)) {
                    $parts = explode('.', $row->target_field);
                    $record = $parts[0] ?? null;
                    if ($record) {
                        // Map record segment to UI entity key
                        $map = [
                            'person' => 'person',
                            'address' => 'person_addresses',
                            'phone' => 'person_phones',
                            'email' => 'emails',
                            'account' => 'accounts',
                            'contract' => 'contracts',
                        ];
                        $entity = $map[$record] ?? $record;
                    }
                }
                if ($entity) {
                    DB::table('import_mappings')->where('id', $row->id)->update(['entity' => $entity]);
                }
            }
        });
    }

    public function down(): void
    {
        Schema::table('import_mappings', function (Blueprint $table) {
            if (Schema::hasColumn('import_mappings', 'entity')) {
                // drop composite index if exists
                try {
                    $table->dropIndex(['import_id', 'entity']);
                } catch (\Throwable $e) { /* ignore */
                }
                $table->dropColumn('entity');
            }
        });
    }
};
