package de.assecutor.votianlt.config;

import com.vaadin.flow.server.VaadinServiceInitListener;
import de.assecutor.votianlt.service.DemoModeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DemoSessionCleanupConfig {

    private static final Logger log = LoggerFactory.getLogger(DemoSessionCleanupConfig.class);

    @Bean
    public VaadinServiceInitListener demoSessionCleanupListener(DemoModeService demoModeService) {
        return event -> event.getSource().addSessionDestroyListener(sessionDestroyEvent -> {
            try {
                var wrappedSession = sessionDestroyEvent.getSession().getSession();
                if (wrappedSession != null) {
                    demoModeService.cleanupAndReleaseIfOwned(wrappedSession.getId());
                }
            } catch (Exception ex) {
                log.warn("Demo session destroy cleanup failed: {}", ex.getMessage(), ex);
            }
        });
    }
}
