package mx.gob.jumapacelaya.services;

import com.vaadin.flow.server.VaadinService;
import mx.gob.jumapacelaya.api.RedmineClient;
import mx.gob.jumapacelaya.services.SecurityService;
import mx.gob.jumapacelaya.models.CustomUserDetails;
import mx.gob.jumapacelaya.models.RedmineUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


@Service
public class UserService {
    private final SecurityService securityService;
    private final RedmineClient redmineClient;
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    private final LdapService ldpaService;

    public UserService(SecurityService securityService, RedmineClient redmineClient, LdapService ldpaService) {
        this.securityService = securityService;
        this.redmineClient = redmineClient;
        this.ldpaService = ldpaService;
    }


    public RedmineUser getAuthenticatedRedmineUser() {
        try {
            String username = securityService.getAuthenticatedUser();
            logger.info("Usuario autenticado: " + username);
            if (username != null) {
                RedmineUser user = redmineClient.getUserByUsername(username);
                if (user == null) {
                    CustomUserDetails userDetails = ldpaService.getUserDetails(username);
                    if (userDetails != null) {
                        if (userDetails.getEmail() == null || userDetails.getEmail().isEmpty()) {
                            logger.error("El usuario: " + username + " no tiene correo electronico.");
                            return null;
                        }
                        RedmineUser newUser = RedmineClient.createRedmineUser(
                                username,
                                userDetails.getFirstName(),
                                userDetails.getLastName(),
                                userDetails.getEmail()
                        );
                        if (newUser != null) {
                            logger.info("Usuario creado en Redmine: " + newUser);
                            return newUser;
                        } else {
                            logger.error("Error al crear el usuario en Redmine");
                        }
                    } else {
                        logger.error("No se encontraron detalles del usuario en LDAP");
                    }
                } else {
                    logger.info("Usuario autenticado en Redmine: " + user);
                }
                return user;
            }
        } catch (Exception e) {
            logger.error("Error al obtener al usuario autenticado en Redmine", e);
        }
        return null;
    }

    public RedmineUser getRedmineUser() {

        RedmineUser userclient = (RedmineUser) VaadinService.getCurrentRequest().getWrappedSession().getAttribute("myaccount");

        if (userclient == null) {
            RedmineUser user = getAuthenticatedRedmineUser();
            if (user != null) {
                RedmineUser myAccount = redmineClient.getMyAccount(user.getLogin());
                if (myAccount != null && !myAccount.getKey().isEmpty()) {
                    userclient = myAccount;
                    VaadinService.getCurrentRequest().getWrappedSession().setAttribute("myaccount", myAccount);
                } else {
                    // Crear un nuevo usuario si no existe
                    myAccount = RedmineClient.createRedmineUser(user.getLogin(), user.getFirstname(), user.getLastname(), user.getMail());
                    if (myAccount != null && !myAccount.getKey().isEmpty()) {
                        userclient = myAccount;
                        VaadinService.getCurrentRequest().getWrappedSession().setAttribute("myaccount", myAccount);
                    }
                }
            }
        }
        return userclient;
    }
}
