package com.escolapios.fctmongo.entity; // 👈 Asegúrate de usar tu paquete de Mongo

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.data.annotation.Id; // 👈 IMPORTANTE: Usar el Id de Spring Data, NO el de jakarta
import org.springframework.data.mongodb.core.mapping.Document; // 👈 Colección de MongoDB
import lombok.AllArgsConstructor;
import lombok.Data; // 👈 Cambiado a @Data para simplificar (incluye Getter, Setter, etc.)
import lombok.NoArgsConstructor;

@Document(collection = "documentos") // 👈 Define la colección en tu base de datos NoSQL
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Documento {

    @Id // MongoDB generará un String alfanumérico automático (ObjectId) si se guarda vacío
    private String id;
    
    private String cursoAcademico;
    private String convenioId; // Cambiado a String para conectar con el convenio de Mongo

    // En MongoDB las listas se guardan de forma EMBEBIDA (subdocumentos anidados).
    // Ya no necesitas tablas intermedias como "documento_alumnos" ni anotaciones @ManyToMany.
    private List<Alumno> alumnos = new ArrayList<>();    
    
    private String tipo;
    private String nombreFichero;
    private String ruta;
    private String rutaPdf;
    private LocalDateTime fechaGeneracion;
    // 🟢 NUEVO ATRIBUTO DE CONTROL EN MONGODB
    private String estado;        // "PENDIENTE", "APROBADO", "FIRMADO"
    /**
     * 🟢 Lee y retorna el contenido binario (byte[]) del archivo PDF desde el disco del servidor
     */
    public byte[] getBytes() {
        try {
            // 1. Priorizamos la ruta específica del PDF, si está vacía usamos la ruta general
            String rutaDestino = (this.rutaPdf != null && !this.rutaPdf.trim().isEmpty()) 
                    ? this.rutaPdf 
                    : this.ruta;

            if (rutaDestino == null || rutaDestino.trim().isEmpty()) {
                System.err.println("❌ No se puede leer el archivo: El documento con ID " + this.id + " no tiene ninguna ruta guardada.");
                return null;
            }

            // 2. Convertimos la cadena de texto en un objeto Path de Java NIO
            java.nio.file.Path path = java.nio.file.Paths.get(rutaDestino);

            // 3. Comprobamos si el archivo existe físicamente en el servidor antes de leerlo
            if (java.nio.file.Files.exists(path)) {
                // Leemos todos los bytes del archivo PDF en un único paso atómico
                return java.nio.file.Files.readAllBytes(path);
            } else {
                System.err.println("❌ Error de almacenamiento: El archivo físico no existe en la ruta: " + rutaDestino);
                return null;
            }

        } catch (Exception e) {
            System.err.println("❌ Excepción al leer los bytes del documento PDF: " + e.getMessage());
            return null;
        }
    }

}
