<?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('ordenes_trabajo', function (Blueprint $table) {
            $table->id();
            $table->string('codigo', 30)->unique();
            $table->string('clase', 20)->default('preventivo')->comment('preventivo, correctivo');
            $table->foreignId('plan_id')->nullable()->constrained('planes_mantenimiento')->nullOnDelete();
            $table->foreignId('area_id')->nullable()->constrained('areas')->nullOnDelete();
            $table->foreignId('sistema_id')->nullable()->constrained('sistemas')->nullOnDelete();
            $table->foreignId('equipo_id')->nullable()->constrained('equipos')->nullOnDelete();
            $table->foreignId('estado_id')->nullable()->constrained('estados_orden')->nullOnDelete();
            $table->foreignId('prioridad_id')->nullable()->constrained('prioridades')->nullOnDelete();
            $table->foreignId('responsable_id')->nullable()->constrained('usuarios')->nullOnDelete();
            $table->foreignId('creado_por')->nullable()->constrained('usuarios')->nullOnDelete();
            $table->foreignId('aprobado_por')->nullable()->constrained('usuarios')->nullOnDelete();
            $table->foreignId('cerrado_por')->nullable()->constrained('usuarios')->nullOnDelete();
            $table->date('fecha_programada')->nullable();
            $table->datetime('fecha_inicio')->nullable();
            $table->datetime('fecha_cierre')->nullable();
            $table->datetime('fecha_aprobacion')->nullable();
            $table->datetime('fecha_vencimiento')->nullable();
            $table->decimal('horometro_inicio', 12, 2)->nullable();
            $table->decimal('horometro_fin', 12, 2)->nullable();
            $table->decimal('costo_mano_obra', 14, 2)->default(0);
            $table->decimal('costo_repuestos', 14, 2)->default(0);
            $table->decimal('costo_otros', 14, 2)->default(0);
            $table->decimal('costo_total', 14, 2)->default(0);
            $table->text('descripcion')->nullable();
            $table->text('observaciones')->nullable();
            $table->text('observaciones_cierre')->nullable();
            $table->string('firma_responsable', 255)->nullable();
            $table->string('firma_supervisor', 255)->nullable();
            $table->timestamps();
            $table->softDeletes();
            $table->index(['fecha_programada', 'estado_id']);
            $table->index(['equipo_id', 'fecha_programada']);
        });

        Schema::create('ordenes_responsables', function (Blueprint $table) {
            $table->id();
            $table->foreignId('orden_id')->constrained('ordenes_trabajo')->cascadeOnDelete();
            $table->foreignId('usuario_id')->constrained('usuarios')->cascadeOnDelete();
            $table->string('rol', 30)->default('secundario')->comment('principal, secundario, supervisor');
            $table->timestamps();
            $table->unique(['orden_id', 'usuario_id']);
        });

        Schema::create('ordenes_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('orden_id')->constrained('ordenes_trabajo')->cascadeOnDelete();
            $table->foreignId('plan_item_id')->nullable()->constrained('planes_items')->nullOnDelete();
            $table->integer('numero_item')->default(0);
            $table->text('descripcion');
            $table->string('estado_item', 20)->default('pendiente')->comment('pendiente, realizado, no_aplica, no_realizado');
            $table->boolean('lila_l_limpieza')->default(false);
            $table->boolean('lila_i_inspeccion')->default(false);
            $table->boolean('lila_l_lubricacion')->default(false);
            $table->boolean('lila_a_ajuste')->default(false);
            $table->string('lectura_condicion', 100)->nullable();
            $table->text('observaciones')->nullable();
            $table->datetime('ejecutado_en')->nullable();
            $table->foreignId('ejecutado_por')->nullable()->constrained('usuarios')->nullOnDelete();
            $table->timestamps();
            $table->index(['orden_id', 'numero_item']);
        });

        Schema::create('ordenes_fotos', function (Blueprint $table) {
            $table->id();
            $table->foreignId('orden_id')->constrained('ordenes_trabajo')->cascadeOnDelete();
            $table->foreignId('orden_item_id')->nullable()->constrained('ordenes_items')->cascadeOnDelete();
            $table->string('ruta', 255);
            $table->string('miniatura', 255)->nullable();
            $table->string('tipo', 20)->default('antes')->comment('antes, despues, evidencia, placa, manual, firma, otro');
            $table->string('descripcion', 255)->nullable();
            $table->foreignId('subido_por')->nullable()->constrained('usuarios')->nullOnDelete();
            $table->timestamps();
        });

        Schema::create('ordenes_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('orden_id')->constrained('ordenes_trabajo')->cascadeOnDelete();
            $table->foreignId('usuario_id')->nullable()->constrained('usuarios')->nullOnDelete();
            $table->string('accion', 50);
            $table->string('estado_anterior', 30)->nullable();
            $table->string('estado_nuevo', 30)->nullable();
            $table->text('detalle')->nullable();
            $table->json('metadata')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('ordenes_logs');
        Schema::dropIfExists('ordenes_fotos');
        Schema::dropIfExists('ordenes_items');
        Schema::dropIfExists('ordenes_responsables');
        Schema::dropIfExists('ordenes_trabajo');
    }
};
