package cn.bunny.springdemo.configuration;

import cn.bunny.springdemo.dao.entity.AdminUser;
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.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import java.util.ArrayList;

@Configuration
public class SecurityConfiguration {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new SCryptPasswordEncoder(4, 8, 1, 8, 32);
    }

    /**
     * 使用内存方式
     *
     * @param encoder 密码加密器
     * @return 基于内存的用户
     */
    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder encoder) {
        ArrayList<UserDetails> userDetails = new ArrayList<>();
        userDetails.add(new AdminUser("admin", encoder.encode("admin"), true));
        userDetails.add(new AdminUser("bunny", encoder.encode("password"), true));

        return new InMemoryUserDetailsManager(userDetails);
    }

    // /**
    //  * 使用数据库方式
    //  *
    //  * @param userService 获取用户数据（如数据库）
    //  * @return 基于数据库的用户
    //  */
    // @Bean
    // public UserDetailsService userDetailsService(UserService userService) {
    //     return username -> {
    //         AdminUser adminUser = userService.getOne(Wrappers.<AdminUser>lambdaQuery().eq(AdminUser::getUsername, userService));
    //         if (adminUser != null) {
    //             return adminUser;
    //         }
    //         throw new UsernameNotFoundException("未找到 AdminUser");
    //     };
    // }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity security) throws Exception {
        return security
                .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
                        authorizationManagerRequestMatcherRegistry
                                .requestMatchers("/order").hasRole("USER")// 请求需要含有USER角色
                                .requestMatchers("/", "/index", "/login", "/images/**").permitAll()
                )
                /* 自定义登录页面 */
                // .formLogin(AbstractAuthenticationFilterConfigurer::permitAll)// 默认的登录页会自动启用，无需额外配置
                .formLogin(formLoginConfigurer -> formLoginConfigurer
                                .loginPage("/login")
                                // .loginProcessingUrl("/authenticate")
                                .usernameParameter("username")// 自定义用户名名称
                                .usernameParameter("password")// 自定义密码名称
                                .defaultSuccessUrl("/index")// 登录成功后默认跳转页面
                        // .defaultSuccessUrl("/index", true)// 登录成功后默认跳转页面，如果用户之前访问页面也需要强制跳转到 /index 可以传递第二个参数
                )
                // .csrf(AbstractHttpConfigurer::disable)// 前后端分离可以禁用
                .build();
    }
}
