<?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('fixed_asset_movements', function (Blueprint $table) {
            $table->id();
            $table->foreignId('fixed_asset_id')
                  ->constrained('fixed_assets')->onDelete('cascade');

            $table->enum('movement_type', [
                'received',
                'allocated',
                'transferred',
                'returned',
                'maintenance_start',
                'maintenance_end',
                'disposed',
                'retired',
                'condition_change',
                'location_change',
                'incoming',
                'allocation',
                'return',
                'maintenance',
                'maintenance_complete',
                'disposal',
            ]);
            $table->dateTime('movement_date')->nullable();

            $table->string('reference_type')->nullable();
            $table->unsignedBigInteger('reference_id')->nullable();

            // State snapshot
            $table->string('from_location', 255)->nullable();
            $table->string('to_location', 255)->nullable();
            $table->unsignedBigInteger('from_project_id')->nullable();
            $table->unsignedBigInteger('to_project_id')->nullable();
            $table->unsignedBigInteger('from_division_id')->nullable();
            $table->unsignedBigInteger('to_division_id')->nullable();
            $table->string('condition_before', 20)->nullable();
            $table->string('condition_after', 20)->nullable();
            $table->string('lifecycle_status_before', 30)->nullable();
            $table->string('lifecycle_status_after', 30)->nullable();

            // People
            $table->foreignId('user_id')->nullable()
                  ->constrained('users')->onDelete('set null');
            $table->foreignId('performed_by')->nullable()
                  ->constrained('users')->onDelete('set null');
            $table->text('notes')->nullable();
            $table->timestamps();

            $table->index(['fixed_asset_id', 'movement_type'], 'fa_movement_asset_type_idx');
            $table->index('movement_date', 'fa_movement_date_idx');
            $table->index('created_at', 'fa_movement_created_idx');
            $table->index('movement_type', 'fa_movement_type_idx');
        });
    }

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