package com.dbnt.kcgfilemanager.config;

import com.dbnt.kcgfilemanager.service.UserInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserInfoService userInfoService;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new Pbkdf2PasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**", "/img/**", "/js/**", "/vendor/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() // 페이지 권한 설정
                .antMatchers("/board/**").hasRole(Role.USER.name()) // USER, ADMIN 접근 허용
                .antMatchers("/info/**").hasRole(Role.USER.name()) // USER, ADMIN 접근 허용
                .antMatchers("/admin/**").hasRole(Role.ADMIN.name()) // ADMIN만 접근 허용
                .antMatchers("/user/login").permitAll() // 로그인 페이지는 권한 없이 접근 허용
            .and() // 로그인 설정
                .formLogin() .loginPage("/user/login") // Custom login form 사용
                .failureUrl("/login-error") // 로그인 실패 시 이동
                .defaultSuccessUrl("/") // 로그인 성공 시 redirect 이동
            .and() // 로그아웃 설정
                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")) // 로그아웃 시 URL 재정의
                .logoutSuccessUrl("/") // 로그아웃 성공 시 redirect 이동
                .invalidateHttpSession(true) // HTTP Session 초기화
                .deleteCookies("JSESSIONID") // 특정 쿠키 제거
            .and() // 403 예외처리 핸들링
                .exceptionHandling().accessDeniedPage("/denied");
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userInfoService).passwordEncoder(passwordEncoder());
    }
}
