<?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
    {
        if (Schema::hasTable('warehouses') && Schema::hasTable('warehouse_types')) {
            Schema::table('warehouses', function (Blueprint $table) {
                // warehouse_type_id -> warehouse_types.id
                $table->foreign('warehouse_type_id', 'wh_type_fk')
                    ->references('id')->on('warehouse_types')
                    ->onUpdate('cascade')->nullOnDelete();
            });
        }

        if (Schema::hasTable('warehouses') && Schema::hasTable('users')) {
            Schema::table('warehouses', function (Blueprint $table) {
                // created_by / updated_by -> users.id
                $table->foreign('created_by', 'wh_created_by_fk')
                    ->references('id')->on('users')
                    ->onUpdate('cascade')->nullOnDelete();

                $table->foreign('updated_by', 'wh_updated_by_fk')
                    ->references('id')->on('users')
                    ->onUpdate('cascade')->nullOnDelete();
            });
        }
    }

    public function down(): void
    {
        if (Schema::hasTable('warehouses')) {
            Schema::table('warehouses', function (Blueprint $table) {
                foreach (['wh_type_fk', 'wh_created_by_fk', 'wh_updated_by_fk'] as $fk) {
                    try { $table->dropForeign($fk); } catch (\Throwable $e) {}
                }
            });
        }
    }
};

