package com.escolapios.fctmongo.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import lombok.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "convenios")
public class Convenio {

    @Id
    private String id;

    private String numeroAcuerdo;
    private String estado;
    private String asumeSeguridadSocial;
    private LocalDate fechaFirma;
    private String cursoAcademico;
    private String observaciones;

    // 🏢 Empresa: Una única entidad asignada por convenio
    @Field("empresa")
    private Empresa empresa;

    // 👨‍🏫 Colecciones Multi-Entidad (Estructuras completas integradas en arrays)
    @Field("profesores")
    private List<Profesor> profesores = new ArrayList<>();

    @Field("tutoresEmpresa")
    private List<TutorEmpresa> tutoresEmpresa = new ArrayList<>();

    // Añadir esto dentro de Convenio.java junto a las otras listas:
    @Field("contactos")
    private List<ContactoEmpresa> contactos = new ArrayList<>(); 
    // (O el nombre de la clase que uses para las personas con rol de contacto)

    @Field("familiasProfesionales")
    private List<FamiliaProfesional> familiasProfesionales = new ArrayList<>();

    @Field("ciclos")
    private List<CicloFormativo> ciclos = new ArrayList<>();

    @Field("alumnos")
    private List<Alumno> alumnos = new ArrayList<>();

    @Field("valoraciones")
    private List<ValoracionEmpresa> valoraciones = new ArrayList<>();

    // =========================================================================
    // 🎯 GETTERS PUENTE DE LOMBOK REQUERIDOS POR EL MOTOR DE PLANTILLAS {{ ... }}
    // =========================================================================
    
    // 🏢 Mapeo Plano de Empresa
    @Getter(AccessLevel.PUBLIC) public String empresaId = "";
    @Getter(AccessLevel.PUBLIC) public String empresaNombre = "";
    @Getter(AccessLevel.PUBLIC) public String empresaDireccion = "";
    @Getter(AccessLevel.PUBLIC) public String cif = "";
    @Getter(AccessLevel.PUBLIC) public String municipio = "";
    @Getter(AccessLevel.PUBLIC) public String provincia = "";
    @Getter(AccessLevel.PUBLIC) public String cp = "";
    @Getter(AccessLevel.PUBLIC) public String actividad = "";
    @Getter(AccessLevel.PUBLIC) public String contacto = ""; // 🟢 Sincronizado exactamente con {{ contacto }} de tu log
    @Getter(AccessLevel.PUBLIC) public String escrituraCargo = "";
    @Getter(AccessLevel.PUBLIC) public String pais = "";

    // 👨‍🏫 Mapeo Plano del Profesor Principal (Índice 0 del array)
    @Getter(AccessLevel.PUBLIC) public String profesorId = "";
    @Getter(AccessLevel.PUBLIC) public String nombreProfesor = "";
    @Getter(AccessLevel.PUBLIC) public String apellidosProfesor = "";
    @Getter(AccessLevel.PUBLIC) public String dniProfesor = "";
    @Getter(AccessLevel.PUBLIC) public String emailProfesor = "";

    // 👔 Mapeo Plano del Tutor de Empresa Principal (Índice 0 del array)
    @Getter(AccessLevel.PUBLIC) public String tutorEmpresaId = "";
    @Getter(AccessLevel.PUBLIC) public String tutorEmpresaNombre = "";
    @Getter(AccessLevel.PUBLIC) public String tutorEmpresaApellidos = "";
    @Getter(AccessLevel.PUBLIC) public String tutorEmpresaDni = "";
    @Getter(AccessLevel.PUBLIC) public String tutorEmpresaEmail = "";
    
    // Contactos (Raíz secundaria si existiera)
    @Getter(AccessLevel.PUBLIC) public String contactoId = "";
    @Getter(AccessLevel.PUBLIC) public String contactoNombre = "";
    @Getter(AccessLevel.PUBLIC) public String contactoApellidos = "";
    @Getter(AccessLevel.PUBLIC) public String contactoDni = "";
    @Getter(AccessLevel.PUBLIC) public String contactoEmail = "";
    
    // 🎓 Mapeo Plano de la Familia Profesional Principal (Índice 0 del array)
    @Getter(AccessLevel.PUBLIC) public String familiaProfesionalIdStr = "";
    @Getter(AccessLevel.PUBLIC) public String familiaProfesionalNombreStr = "";

    // 👥 Alumno Activo
    @Getter(AccessLevel.PUBLIC) public String alumnoNombre = "sin-nombre";
    @Getter(AccessLevel.PUBLIC) public String alumnoApellidos = "";
    @Getter(AccessLevel.PUBLIC) public String alumnoDni = "";
    @Getter(AccessLevel.PUBLIC) public String alumnoCiclo = "";

    /**
     * ⚡ Sincroniza campos planos extrayendo de forma segura la primera posición de los arrays NoSQL
     */
    public void sincronizarCamposPlanosTemplate() {
               // 1. Sincronización de Empresa Única
        if (this.empresa != null) {
            this.empresaId = this.empresa.getId() != null ? this.empresa.getId() : "";
            this.empresaNombre = this.empresa.getNombre() != null ? this.empresa.getNombre() : "";
            this.empresaDireccion = this.empresa.getDireccion() != null ? this.empresa.getDireccion() : "";
            this.cif = this.empresa.getCif() != null ? this.empresa.getCif() : "";
            this.municipio = this.empresa.getMunicipio() != null ? this.empresa.getMunicipio() : "";
            this.provincia = this.empresa.getProvincia() != null ? this.empresa.getProvincia() : "";
            this.cp = this.empresa.getCp() != null ? this.empresa.getCp() : "";
            this.actividad = this.empresa.getActividad() != null ? this.empresa.getActividad() : "";
            this.pais = this.empresa.getPais() != null ? this.empresa.getPais() : "";
            this.escrituraCargo = this.empresa.getEscrituraCargo() != null ? this.empresa.getEscrituraCargo() : "Representante Legal";

            // 🟢 SOLUCIÓN MAESTRA PARA EL CONTACTO:
            // Extraemos el primer contacto de la empresa si existe
            if (this.empresa.getContactos() != null && !this.empresa.getContactos().isEmpty()) {
                ContactoEmpresa firmante = this.empresa.getContactos().get(0);
                this.contacto = firmante.getNombre() != null ? firmante.getNombre() : "";
                if (firmante.getCargo() != null) this.escrituraCargo = firmante.getCargo();
            } else {
                this.contacto = "";
            }
        }

        // 2. Sincronización del Primer Profesor del Array
        if (this.profesores != null && !this.profesores.isEmpty() && this.profesores.get(0) != null) {
            Profesor p = this.profesores.get(0);
            this.profesorId = p.getId() != null ? p.getId() : "";
            this.nombreProfesor = p.getNombre() != null ? p.getNombre() : "";
            this.apellidosProfesor = p.getApellidos() != null ? p.getApellidos() : "";
            this.dniProfesor = p.getDni() != null ? p.getDni() : "";
            this.emailProfesor = p.getEmail() != null ? p.getEmail() : "";
        }

        // 3. Sincronización del Primer Tutor de Empresa del Array
        if (this.tutoresEmpresa != null && !this.tutoresEmpresa.isEmpty() && this.tutoresEmpresa.get(0) != null) {
            TutorEmpresa t = this.tutoresEmpresa.get(0);
            this.tutorEmpresaId = t.getId() != null ? t.getId() : "";
            this.tutorEmpresaNombre = t.getNombre() != null ? t.getNombre() : "";
            this.tutorEmpresaApellidos = t.getApellidos() != null ? t.getApellidos() : "";
            this.tutorEmpresaDni = t.getDni() != null ? t.getDni() : "";
            this.tutorEmpresaEmail = t.getEmail() != null ? t.getEmail() : "";
        }

        // Sincronización secundaria opcional de contactos en la raíz
        if (this.contactos != null && !this.contactos.isEmpty() && this.contactos.get(0) != null) {
            ContactoEmpresa con = this.contactos.get(0);
            this.contactoId = con.getId() != null ? con.getId() : "";
            this.contactoNombre = con.getNombre() != null ? con.getNombre() : "";
            this.contactoApellidos = con.getApellidos() != null ? con.getApellidos() : "";
            this.contactoDni = con.getDni() != null ? con.getDni() : "";
            this.contactoEmail = con.getEmail() != null ? con.getEmail() : "";
        }

        // 4. Sincronización de la Primera Familia Profesional del Array
        if (this.familiasProfesionales != null && !this.familiasProfesionales.isEmpty() && this.familiasProfesionales.get(0) != null) {
            FamiliaProfesional f = this.familiasProfesionales.get(0);
            this.familiaProfesionalIdStr = f.getId() != null ? f.getId() : "";
            this.familiaProfesionalNombreStr = f.getNombre() != null ? f.getNombre() : "";
        }

        // 5. Sincronización del Primer Alumno Vinculado
        if (this.alumnos != null && !this.alumnos.isEmpty() && this.alumnos.get(0) != null) {
            Alumno a = this.alumnos.get(0);
            this.alumnoNombre = a.getNombre() != null ? a.getNombre() : "";
            this.alumnoApellidos = a.getApellidos() != null ? a.getApellidos() : "";
            this.alumnoDni = a.getDni() != null ? a.getDni() : "";    
        }

        // 6. 🟢 COMPLETADO DE LÍNEAS FINALES DEL CICLO FORMATIVO:
        if (this.ciclos != null && !this.ciclos.isEmpty() && this.ciclos.get(0) != null) {
            CicloFormativo c = this.ciclos.get(0);
            this.alumnoCiclo = c.getNombre() != null ? c.getNombre() : "";
        } else {
            this.alumnoCiclo = "";
        }
        this.cursoAcademico = this.cursoAcademico != null ? this.cursoAcademico : "";
    }

    public List<Alumno> getAlumnosOriginales() { 
        return this.alumnos; 
    }

}
