package mx.gob.jumapacelaya.services;

import mx.gob.jumapacelaya.models.CustomUserDetails;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.stereotype.Service;

import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import java.util.List;

@Service
public class LdapService {

    private final LdapTemplate ldapTemplate;


    public LdapService(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }

    public CustomUserDetails getUserDetails(String username) {
        EqualsFilter filter = new EqualsFilter("sAMAccountName", username);
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchControls.setReturningAttributes(new String[]{"givenName", "sn", "mail"});
        searchControls.setReturningObjFlag(false);

        List<CustomUserDetails> result = ldapTemplate.search("", filter.encode(), searchControls, (Attributes attrs) -> {
            String firstName = getAttribute(attrs, "givenName");
            String lastName = getAttribute(attrs, "sn");
            String email = getAttribute(attrs, "mail");
            return new CustomUserDetails(username, firstName, lastName, email, null, null); // Ajustar los últimos dos parámetros si es necesario
        });
        return result.isEmpty() ? null : result.get(0);
    }

    private String getAttribute(Attributes attributes, String attributeName) {
        try {
            return attributes.get(attributeName) != null ? attributes.get(attributeName).get().toString(): null;
        } catch (NamingException e) {
            return null;
        }
    }
}
