// ====================================
// ESQUEMA DE MONGODB - DETALLADO
// ====================================

// COLECCIÓN: usuarios
// BASE DE DATOS: registro-app

/*
  ESTRUCTURA DEL DOCUMENTO:
  
  {
    _id: ObjectId("5f3a7e4c8b9c7d6e5f4c3b2a"),    // ID automático de MongoDB
    nombre: String,                                // Nombre del usuario (3+ caracteres)
    grupo: String,                                 // Grupo/clase del usuario
    telefono: String,                              // Teléfono único (7-15 dígitos)
    fechaRegistro: Date                            // Fecha de creación (automática)
  }
*/

// EJEMPLO DE DOCUMENTO:
/*
{
  "_id": ObjectId("6581f3a4c9d1e2f3g4h5i6j7"),
  "nombre": "Juan Pérez García",
  "grupo": "1º DAM",
  "telefono": "612345678",
  "fechaRegistro": ISODate("2024-01-15T10:30:00.000Z")
}
*/

// ====================================
// VALIDACIONES EN MONGODB
// ====================================

// El índice único se crea automáticamente:
db.usuarios.createIndex({ telefono: 1 }, { unique: true })

// ====================================
// COMANDOS ÚTILES EN MONGOSH
// ====================================

/*
1. CONEXIÓN
   mongosh

2. SELECCIONAR BASE DE DATOS
   use registro-app

3. VER TODAS LAS COLECCIONES
   show collections

4. VER TODOS LOS USUARIOS
   db.usuarios.find()

5. VER EN FORMATO TABLA
   db.usuarios.find().pretty()

6. CONTAR DOCUMENTOS
   db.usuarios.countDocuments()

7. BUSCAR POR TELÉFONO
   db.usuarios.findOne({ telefono: "612345678" })

8. BUSCAR POR NOMBRE
   db.usuarios.find({ nombre: { $regex: "Juan" } })

9. VER UN USUARIO ESPECÍFICO
   db.usuarios.findOne({ _id: ObjectId("...") })

10. ACTUALIZAR UN USUARIO
    db.usuarios.updateOne(
      { _id: ObjectId("...") },
      { $set: { nombre: "Nuevo Nombre" } }
    )

11. ELIMINAR UN USUARIO
    db.usuarios.deleteOne({ _id: ObjectId("...") })

12. ELIMINAR TODOS LOS USUARIOS
    db.usuarios.deleteMany({})

13. VER ÍNDICES
    db.usuarios.getIndexes()

14. VER ESTADÍSTICAS DE LA COLECCIÓN
    db.usuarios.stats()

15. EXPORTAR A JSON (desde terminal)
    mongoexport --db registro-app --collection usuarios --out usuarios.json
*/

// ====================================
// VIOLACIONES DE VALIDACIÓN
// ====================================

/*
1. TELÉFONO DUPLICADO (ÚNICO CONSTRAINT)
   Error: E11000 duplicate key error collection: registro-app.usuarios index: telefono_1 dup key: { : "612345678" }

2. NOMBRE FALTANTE (REQUERIDO)
   Error: ValidationError: nombre: Path `nombre` is required.

3. TELÉFONO INVÁLIDO (FORMATO)
   Error: ValidationError: telefono: Path `telefono` failed validation

4. NOMBRE MUY CORTO
   Error: ValidationError: nombre: Path `nombre` is too short (0 < 3)
*/

// ====================================
// DATOS DE EJEMPLO
// ====================================

/*
Insertar múltiples usuarios:

db.usuarios.insertMany([
  {
    nombre: "Juan Pérez",
    grupo: "1º DAM",
    telefono: "612345678",
    fechaRegistro: new Date()
  },
  {
    nombre: "María García",
    grupo: "1º DAM",
    telefono: "698765432",
    fechaRegistro: new Date()
  },
  {
    nombre: "Carlos López",
    grupo: "2º DAM",
    telefono: "655123456",
    fechaRegistro: new Date()
  },
  {
    nombre: "Ana Martínez",
    grupo: "1º DAW",
    telefono: "677890123",
    fechaRegistro: new Date()
  }
])
*/

// ====================================
// CONSULTAS AVANZADAS
// ====================================

/*
1. USUARIOS DE UN GRUPO ESPECÍFICO
   db.usuarios.find({ grupo: "1º DAM" })

2. USUARIOS REGISTRADOS HOY
   db.usuarios.find({
     fechaRegistro: {
       $gte: new Date(new Date().setHours(0,0,0,0)),
       $lt: new Date(new Date().setHours(23,59,59,999))
     }
   })

3. CONTAR POR GRUPO
   db.usuarios.aggregate([
     { $group: { _id: "$grupo", count: { $sum: 1 } } }
   ])

4. ORDENAR POR FECHA DESCENDENTE
   db.usuarios.find().sort({ fechaRegistro: -1 })

5. LIMITAR RESULTADOS
   db.usuarios.find().limit(10)

6. SALTAR DOCUMENTOS (PAGINACIÓN)
   db.usuarios.find().skip(10).limit(10)

7. BUSCAR NOMBRES QUE COMIENZAN CON "J"
   db.usuarios.find({ nombre: /^J/ })

8. USUARIOS CON TELÉFONO QUE CONTIENE "123"
   db.usuarios.find({ telefono: /123/ })

9. PROYECTAR (SELECCIONAR CAMPOS)
   db.usuarios.find({}, { nombre: 1, telefono: 1, _id: 0 })

10. ACTUALIZAR MÚLTIPLES
    db.usuarios.updateMany(
      { grupo: "1º DAM" },
      { $set: { grupo: "1º DAM - Actualizado" } }
    )
*/

// ====================================
// BACKUP Y RESTORE
// ====================================

/*
DESDE TERMINAL:

1. BACKUP (EXPORTAR)
   mongoexport --db registro-app --collection usuarios --out backup.json

2. RESTORE (IMPORTAR)
   mongoimport --db registro-app --collection usuarios --file backup.json --jsonArray

3. BACKUP COMPLETO (TODA LA BD)
   mongodump --db registro-app --out ./backup/

4. RESTORE COMPLETO
   mongorestore --db registro-app ./backup/registro-app/
*/

// ====================================
// PROFILER - ANALIZAR RENDIMIENTO
// ====================================

/*
1. ACTIVAR PROFILER
   db.setProfilingLevel(1)

2. VER CONSULTAS LENTAS
   db.system.profile.find({ millis: { $gt: 100 } }).pretty()

3. DESACTIVAR PROFILER
   db.setProfilingLevel(0)
*/

// ====================================
// REPLICACIÓN Y SHARDING
// ====================================

/*
Para aplicaciones en producción:

1. REPLICA SET:
   - Redundancia de datos
   - Failover automático
   
2. SHARDING:
   - Distribuir datos entre servidores
   - Escalar horizontalmente
*/
