<?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_transfer_order_items')) {
            return;
        }

        Schema::table('dberp_transfer_order_items', function (Blueprint $table): void {
            if (! Schema::hasColumn('dberp_transfer_order_items', 'source_batch_id')) {
                $after = Schema::hasColumn('dberp_transfer_order_items', 'product_sku_spec')
                    ? 'product_sku_spec'
                    : 'product_id';

                $table->unsignedBigInteger('source_batch_id')->nullable()->after($after)->comment('来源批次');
                $table->string('batch_no', 64)->nullable()->after('source_batch_id')->comment('批次号快照');
                $table->date('production_date')->nullable()->after('batch_no')->comment('生产日期');
                $table->date('expiry_date')->nullable()->after('production_date')->comment('到期日期');
                $table->unsignedInteger('shelf_life_days')->default(0)->after('expiry_date')->comment('保质期天数');
                $table->json('batch_allocations')->nullable()->after('shelf_life_days')->comment('调出批次分配快照');
                $table->json('serial_numbers')->nullable()->after('batch_allocations')->comment('序列号快照');
                $table->json('destination_batch_allocations')->nullable()->after('serial_numbers')->comment('调入仓批次分配快照');

                $table->foreign('source_batch_id', 'fk_dtoi_batch')->references('id')->on('dberp_inventory_batches')->nullOnDelete();
                $table->index(['source_batch_id'], 'idx_dtoi_batch');
            }
        });
    }

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

        Schema::table('dberp_transfer_order_items', function (Blueprint $table): void {
            $table->dropForeign('fk_dtoi_batch');
            $table->dropIndex('idx_dtoi_batch');
            $table->dropColumn([
                'source_batch_id',
                'batch_no',
                'production_date',
                'expiry_date',
                'shelf_life_days',
                'batch_allocations',
                'serial_numbers',
                'destination_batch_allocations',
            ]);
        });
    }
};
