<?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('importaciones', function (Blueprint $table) {
            $table->id();
            $table->string('archivo_original', 255);
            $table->string('archivo_ruta', 255);
            $table->string('estado', 20)->default('pendiente')->comment('pendiente, procesando, completada, fallida');
            $table->integer('total_filas')->default(0);
            $table->integer('filas_importadas')->default(0);
            $table->integer('filas_error')->default(0);
            $table->text('resumen')->nullable();
            $table->foreignId('usuario_id')->nullable()->constrained('usuarios')->nullOnDelete();
            $table->timestamps();
        });

        Schema::create('importaciones_errores', function (Blueprint $table) {
            $table->id();
            $table->foreignId('importacion_id')->constrained('importaciones')->cascadeOnDelete();
            $table->string('hoja', 100)->nullable();
            $table->integer('numero_fila')->nullable();
            $table->string('mensaje', 500);
            $table->json('datos_originales')->nullable();
            $table->timestamps();
        });

        Schema::create('bitacora_auditoria', function (Blueprint $table) {
            $table->id();
            $table->foreignId('usuario_id')->nullable()->constrained('usuarios')->nullOnDelete();
            $table->string('accion', 50);
            $table->string('modelo', 100)->nullable();
            $table->unsignedBigInteger('modelo_id')->nullable();
            $table->json('valores_anteriores')->nullable();
            $table->json('valores_nuevos')->nullable();
            $table->string('ip', 45)->nullable();
            $table->string('user_agent', 255)->nullable();
            $table->timestamps();
            $table->index(['modelo', 'modelo_id']);
        });

        Schema::create('notificaciones', function (Blueprint $table) {
            $table->id();
            $table->foreignId('usuario_id')->constrained('usuarios')->cascadeOnDelete();
            $table->string('titulo', 150);
            $table->text('mensaje')->nullable();
            $table->string('tipo', 30)->default('info');
            $table->string('url', 255)->nullable();
            $table->timestamp('leida_en')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('notificaciones');
        Schema::dropIfExists('bitacora_auditoria');
        Schema::dropIfExists('importaciones_errores');
        Schema::dropIfExists('importaciones');
    }
};
