<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('imports', function (Blueprint $table) {
            if (! Schema::hasColumn('imports', 'import_template_id')) {
                $table->foreignId('import_template_id')->nullable();
            }
            // Add foreign key if not exists (Postgres will error if duplicate, so wrap in try/catch in runtime, but Schema builder doesn't support conditional FKs)
            $table->foreign('import_template_id', 'imports_import_template_id_foreign')
                ->references('id')->on('import_templates')->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('imports', function (Blueprint $table) {
            $table->dropForeign('imports_import_template_id_foreign');
        });
    }
};
