<?php

use App\Extensions\Concerns\ChecksExtensionInstallation;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    use ChecksExtensionInstallation;

    /**
     * Run the migrations.
     */
    public function up(): void
    {
        if (Schema::hasTable('importer_mappings')) {
            return;
        }

        Schema::create('importer_mappings', function (Blueprint $table) {
            $table->id();
            $table->foreignId('job_id')
                ->constrained('importer_jobs')
                ->cascadeOnDelete();
            $table->string('entity_type');
            $table->string('source_id');
            $table->unsignedBigInteger('target_id')->nullable();
            $table->json('meta')->nullable();
            $table->timestamps();

            $table->unique(['job_id', 'entity_type', 'source_id'], 'importer_mappings_unique');
            $table->index(['entity_type', 'source_id'], 'importer_mappings_lookup');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Skip rollback if extension is not installed
        if ($this->shouldSkipRollback('importer')) {
            return;
        }

        Schema::dropIfExists('importer_mappings');
    }
};
