<?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('part_histories', function (Blueprint $table) {
            $table->id();
            $table->foreignId('part_id')->constrained()->onDelete('cascade');
            $table->string('event_type'); // 'created', 'updated', 'stock_in', 'stock_out', 'adjustment', 'price_change', 'supplier_change'
            $table->json('old_values')->nullable(); // Previous values for updates
            $table->json('new_values')->nullable(); // New values for updates
            $table->integer('quantity_change')->nullable(); // For stock movements
            $table->integer('quantity_before')->nullable(); // Stock before change
            $table->integer('quantity_after')->nullable(); // Stock after change
            $table->decimal('cost_before', 10, 2)->nullable(); // Cost before change
            $table->decimal('cost_after', 10, 2)->nullable(); // Cost after change
            $table->string('reference_type')->nullable(); // 'purchase_order', 'service_order', 'manual', 'supplier'
            $table->unsignedBigInteger('reference_id')->nullable(); // ID of related record
            $table->text('notes')->nullable();
            $table->string('ip_address')->nullable();
            $table->text('user_agent')->nullable();
            $table->foreignId('created_by')->constrained('users')->onDelete('cascade');
            $table->timestamps();

            $table->index(['part_id', 'event_type']);
            $table->index(['part_id', 'created_at']);
            $table->index(['event_type', 'created_at']);
            $table->index(['reference_type', 'reference_id']);
        });
    }

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