<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('inventory_adjust_docs', function (Blueprint $table) {
            $table->id();
            $table->string('doc_no')->unique(); // 單號
            $table->foreignId('warehouse_id')->constrained('warehouses')->cascadeOnDelete();
            $table->string('status')->default('draft'); // draft, posted, voided
            $table->string('reason')->nullable(); // 調整原因 (e.g. 報廢, 盤盈虧, 其他)
            $table->string('remarks')->nullable();
            
            // 審核/建立資訊
            $table->timestamp('posted_at')->nullable(); // 過帳時間
            $table->foreignId('created_by')->constrained('users'); 
            $table->foreignId('updated_by')->nullable()->constrained('users');
            $table->foreignId('posted_by')->nullable()->constrained('users');
            
            $table->timestamps();
        });

        Schema::create('inventory_adjust_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('adjust_doc_id')->constrained('inventory_adjust_docs')->cascadeOnDelete();
            $table->foreignId('product_id')->constrained('products');
            $table->string('batch_number')->nullable();
            
            // 記錄當下 "調整前" 的庫存與成本 (參考用)
            $table->decimal('qty_before', 10, 2)->default(0); 
            
            // 實際調整的數量 (可以正負, 正=增加, 負=減少)
            $table->decimal('adjust_qty', 10, 2); 
            
            $table->string('notes')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('inventory_adjust_items');
        Schema::dropIfExists('inventory_adjust_docs');
    }
};
