<?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('positions', function (Blueprint $table) {
            if (!Schema::hasColumn('positions', 'offer_id')) {
                $table->unsignedBigInteger('offer_id')->nullable()->after('id');
                $table->index('offer_id');
            }
        });

        // Add FK if offers table exists
        if (Schema::hasTable('offers')) {
            Schema::table('positions', function (Blueprint $table) {
                // In case FK already exists, ignore (MySQL might throw)
                try {
                    $table->foreign('offer_id')
                        ->references('id')->on('offers')
                        ->onDelete('cascade');
                } catch (\Throwable $e) {
                    // ignore
                }
            });
        }
    }

    public function down(): void
    {
        Schema::table('positions', function (Blueprint $table) {
            // Drop FK if exists
            try { $table->dropForeign(['offer_id']); } catch (\Throwable $e) {}
            try { $table->dropIndex(['offer_id']); } catch (\Throwable $e) {}

            if (Schema::hasColumn('positions', 'offer_id')) {
                $table->dropColumn('offer_id');
            }
        });
    }
};
