package de.assecutor.votianlt.security;

import com.vaadin.flow.server.VaadinSession;
import java.util.Optional;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Service;

@Service
public class SessionAuthenticationService {

    public void storeAuthentication(Authentication authentication) {
        SecurityContextHolder.getContext().setAuthentication(authentication);

        VaadinSession vaadinSession = VaadinSession.getCurrent();
        if (vaadinSession == null) {
            return;
        }

        var wrappedSession = vaadinSession.getSession();
        if (wrappedSession == null) {
            return;
        }

        wrappedSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                SecurityContextHolder.getContext());
    }

    public Optional<String> getCurrentSessionId() {
        VaadinSession vaadinSession = VaadinSession.getCurrent();
        if (vaadinSession == null || vaadinSession.getSession() == null) {
            return Optional.empty();
        }
        return Optional.ofNullable(vaadinSession.getSession().getId());
    }
}
