package kr.iotdoor.boot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers(
                    "/",
                    "/index.do",
                    "/portfolio.do",
                    "/portfolio/**",
                    "/contact.do",
                    "/api/contact",
                    "/comn/file/view/**",
                    "/comn/user/login/login.do",
                    "/comn/user/login/loginUser.do",
                    "/resources/**",
                    "/error",
                    "/actuator/health"
                ).permitAll()
                .requestMatchers("/mfuc/**", "/mngr/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                .loginPage("/comn/user/login/loginUser.do")
                .loginProcessingUrl("/comn/user/login/actionLogin.do")
                .usernameParameter("id")
                .passwordParameter("password")
                .defaultSuccessUrl("/mfuc/index.do", true)
                .failureUrl("/comn/user/login/loginUser.do?login_error=1")
                .permitAll()
            )
            .logout(logout -> logout
                .logoutUrl("/comn/user/login/logout.do")
                .logoutSuccessUrl("/")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
            )
            .rememberMe(Customizer.withDefaults());

        return http.build();
    }

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