<?php

declare(strict_types=1);

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('dberp_purchase_order_items')) {
            return;
        }

        Schema::table('dberp_purchase_order_items', function (Blueprint $table): void {
            if (! Schema::hasColumn('dberp_purchase_order_items', 'requested_warehouse_id')) {
                $table->unsignedBigInteger('requested_warehouse_id')
                    ->nullable()
                    ->after('purchase_request_item_id')
                    ->comment('采购申请目标仓快照');

                $table->foreign('requested_warehouse_id', 'fk_dberp_poi_req_wh')
                    ->references('id')
                    ->on('dberp_warehouses')
                    ->nullOnDelete();

                $table->index(['order_id', 'requested_warehouse_id'], 'idx_dberp_poi_order_req_wh');
            }
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('dberp_purchase_order_items')
            || ! Schema::hasColumn('dberp_purchase_order_items', 'requested_warehouse_id')) {
            return;
        }

        Schema::table('dberp_purchase_order_items', function (Blueprint $table): void {
            $table->dropForeign('fk_dberp_poi_req_wh');
            $table->dropIndex('idx_dberp_poi_order_req_wh');
            $table->dropColumn('requested_warehouse_id');
        });
    }
};
