<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('product_serials', function (Blueprint $table) {
            $table->id();
            $table->ulid('uuid')->unique();
            $table->foreignId('product_id')->constrained('products')->cascadeOnUpdate()->restrictOnDelete();
            // No FK on product_variant_id — matches established convention.
            $table->unsignedBigInteger('product_variant_id')->nullable();
            // Populated only when tracking_mode = batch_serial.
            $table->unsignedBigInteger('stock_batch_id')->nullable();
            // NULL branch_id = sold/disposed (not at a branch location).
            $table->foreignId('branch_id')->nullable()->constrained('warehouses')->cascadeOnUpdate()->nullOnDelete();
            // Current owner (set on sale, cleared on return).
            $table->unsignedBigInteger('current_customer_id')->nullable();

            $table->string('serial_number', 150);

            // Status lookup (context = 'product_serial'): available, reserved, sold,
            // returned, under_repair, damaged, lost, written_off.
            $table->foreignId('status_id')->constrained('statuses')->cascadeOnUpdate()->restrictOnDelete();

            $table->decimal('purchase_price', 12, 2)->nullable();
            $table->date('warranty_expires_at')->nullable();
            $table->text('notes')->nullable();

            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('deleted_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->softDeletes();

            $table->unique(['product_id', 'serial_number']);
            $table->index('product_variant_id');
            $table->index('stock_batch_id');
            $table->index('branch_id');
            $table->index('current_customer_id');
            $table->index('status_id');
        });
    }

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