<?php

declare(strict_types=1);

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

/**
 * 库存精细化：出入库类单据明细批次/序列号快照列（批次流水表已并入 030100）。
 */
return new class extends Migration
{
    public function up(): void
    {
        $tables = [
            'dberp_other_stock_in_order_items' => 'oii',
            'dberp_other_stock_out_order_items' => 'oio',
            'dberp_purchase_receipt_order_items' => 'pri',
            'dberp_purchase_return_order_items' => 'pro',
            'dberp_sales_outbound_order_items' => 'soi',
            'dberp_sales_return_order_items' => 'sri',
        ];

        foreach ($tables as $tableName => $short) {
            Schema::table($tableName, function (Blueprint $table) use ($short): void {
                $table->unsignedBigInteger('source_batch_id')->nullable()->after('product_id')->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->foreign('source_batch_id', 'fk_dberp_'.$short.'_batch')->references('id')->on('dberp_inventory_batches')->nullOnDelete();
                $table->index(['source_batch_id'], 'idx_dberp_'.$short.'_batch');
            });
        }
    }

    public function down(): void
    {
        $tables = [
            'dberp_other_stock_in_order_items' => 'oii',
            'dberp_other_stock_out_order_items' => 'oio',
            'dberp_purchase_receipt_order_items' => 'pri',
            'dberp_purchase_return_order_items' => 'pro',
            'dberp_sales_outbound_order_items' => 'soi',
            'dberp_sales_return_order_items' => 'sri',
        ];

        foreach ($tables as $tableName => $short) {
            Schema::table($tableName, function (Blueprint $table) use ($short): void {
                $table->dropForeign('fk_dberp_'.$short.'_batch');
                $table->dropIndex('idx_dberp_'.$short.'_batch');
                $table->dropColumn([
                    'source_batch_id',
                    'batch_no',
                    'production_date',
                    'expiry_date',
                    'shelf_life_days',
                    'batch_allocations',
                    'serial_numbers',
                ]);
            });
        }
    }
};
