<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('inventory_serials')) {
            Schema::create('inventory_serials', function (Blueprint $table) {
                $table->id();
                $table->foreignId('company_id')->constrained()->onDelete('cascade');
                $table->foreignId('warehouse_id')->constrained()->onDelete('cascade');
                $table->foreignId('item_id')->constrained('inventory_items')->onDelete('cascade');
                $table->foreignId('batch_id')->nullable()->constrained('inventory_batches')->onDelete('set null');
                $table->string('serial_number');
                $table->enum('status', ['in_stock', 'sold', 'reserved', 'defective', 'returned'])->default('in_stock');
                $table->date('purchase_date')->nullable();
                $table->date('warranty_expiry')->nullable();
                $table->decimal('purchase_price', 10, 2)->default(0);
                $table->foreignId('supplier_id')->nullable()->constrained()->onDelete('set null');
                $table->text('notes')->nullable();
                $table->timestamps();

                // Unique constraint for serial number per company
                $table->unique(['company_id', 'serial_number']);
            });
        }
    }

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