package enea.lecservice.security;

import enea.lecservice.entities.PermissionEnum;
import enea.lecservice.security.jwt.JWTRequestFilter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
@Configuration
@RequiredArgsConstructor
@Profile("!test")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    protected @NonNull UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider;
    protected @NonNull InMemoryUserInfoService userDetailsService;
    protected @NonNull JWTRequestFilter jwtRequestFilter;
    protected @NonNull AuthenticationEntryPointImpl entryPointImpl;
    protected @NonNull AccessDeniedHandler accessDeniedHandlerImpl;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(usernamePasswordAuthenticationProvider);
    }

    @Override
    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    public static class RolePrefixConfiguration {

        @Bean
        public GrantedAuthorityDefaults grantedAuthorityDefaults() {
            return new GrantedAuthorityDefaults("");
        }

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * IMPORTANT: Use hasAuthority or hasAnyAuthority instead of hasRole or hasAnyRole, because on check spring
         * security uses "ROLE_" prefix with role name. In our case it doesn't match "platform-admin" or "registered".
         * REFER: https://www.baeldung.com/spring-security-granted-authority-vs-role for difference between 2 concepts.
         */

        http
            .httpBasic().and()
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers("/index/**").permitAll()
                .antMatchers("/admin/**", "**/admin/**").hasAuthority(PermissionEnum.ADMIN.toString())
                .antMatchers("/utils/**").permitAll()//.hasAuthority(Role.PLATFORM_ADMIN.toString())
                .antMatchers("/user/**", "/data/**").hasAnyAuthority(PermissionEnum.ADMIN.toString(), PermissionEnum.VIEW.toString())
                .antMatchers("/auth/authenticate", "/auth/", "/register/**", "/account/activate/**", "/auth/authenticateWithToken").permitAll()
                .anyRequest().authenticated()
                .and()
            .exceptionHandling()
                .authenticationEntryPoint(entryPointImpl)
                .accessDeniedHandler(accessDeniedHandlerImpl)
                .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}
