<?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('stock_opname_items', function (Blueprint $table) {
            $table->id();

            // Foreign Key ke tabel stock_opnames
            $table->foreignId('stock_opname_id')
                ->constrained('stock_opnames')
                ->onDelete('cascade') // Jika header dihapus, detail ikut terhapus
                ->comment('Relasi ke tabel stock_opnames');

            // Polymorphic Relation - bisa Material atau Sparepart
            $table->morphs('itemable');
            // Ini akan create 2 kolom:
            // - itemable_id (bigint) -> ID dari Material atau Sparepart
            // - itemable_type (varchar) -> 'App\Models\Material' atau 'App\Models\Sparepart'

            // Snapshot Data (simpan data saat itu, tidak terpengaruh perubahan di master)
            $table->string('item_name')->comment('Nama item (snapshot)');
            $table->string('item_code')->nullable()->comment('Kode item (snapshot)');
            $table->string('unit', 20)->comment('Satuan (snapshot)');

            // Quantity Information
            $table->decimal('system_qty', 15, 2)->comment('Qty di sistem saat opname');
            $table->decimal('physical_qty', 15, 2)->comment('Qty hasil hitung fisik');
            $table->decimal('difference', 15, 2)->comment('Selisih (physical_qty - system_qty)');

            // Difference Type (auto calculated di Model)
            $table->enum('difference_type', ['normal', 'surplus', 'shortage'])
                ->default('normal')
                ->comment('normal = tidak ada selisih, surplus = lebih, shortage = kurang');

            // Reason & Notes
            $table->string('reason')->nullable()->comment('Alasan selisih (rusak, hilang, salah catat, dll)');
            $table->text('notes')->nullable()->comment('Catatan tambahan untuk item ini');

            // Timestamps
            $table->timestamps();

            // Indexes untuk performa query
            $table->index('stock_opname_id');
            $table->index('difference_type');
            $table->index(['itemable_id', 'itemable_type']); // Composite index untuk polymorphic
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('stock_opname_items');
    }
};
