package de.assecutor.votianlt.security;

import com.vaadin.flow.spring.security.VaadinWebSecurity;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends VaadinWebSecurity {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Konfiguriere zusätzliche öffentliche Endpunkte vor der Basis-Konfiguration
        http.authorizeHttpRequests(auth -> auth
                // Öffentliche Endpunkte
                .requestMatchers(new AntPathRequestMatcher("/"), new AntPathRequestMatcher("/register"),
                        new AntPathRequestMatcher("/login"), new AntPathRequestMatcher("/forget-password"),
                        new AntPathRequestMatcher("/forgot-password-request"), new AntPathRequestMatcher("/images/**"),
                        new AntPathRequestMatcher("/icons/**"), new AntPathRequestMatcher("/favicon.ico"),
                        new AntPathRequestMatcher("/robots.txt"), new AntPathRequestMatcher("/manifest.webmanifest"),
                        new AntPathRequestMatcher("/sw.js"), new AntPathRequestMatcher("/offline.html"),
                        new AntPathRequestMatcher("/frontend/**"), new AntPathRequestMatcher("/webjars/**"),
                        new AntPathRequestMatcher("/h2-console/**"),
                        new AntPathRequestMatcher("/frontend-es5/**", "/frontend-es6/**"),
                        new AntPathRequestMatcher("/mcp/**"), new AntPathRequestMatcher("/ws/**"))
                .permitAll());

        // Standard-CSRF-Konfiguration
        http.csrf(csrf -> csrf.ignoringRequestMatchers(new AntPathRequestMatcher("/h2-console/**"),
                new AntPathRequestMatcher("/ws/**")));

        // Delegiere die Basis-Konfiguration an VaadinWebSecurity
        // Dies fügt automatisch .anyRequest().authenticated() hinzu
        super.configure(http);

        // Setze die Login-View (per Pfad, um Router-Resolution-Probleme zu vermeiden)
        setLoginView(http, "/login");

        // Logout-Konfiguration
        http.logout(logout -> logout.logoutUrl("/logout").logoutSuccessUrl("/").invalidateHttpSession(true)
                .deleteCookies("JSESSIONID"));
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }
}
