
package com.weighttracker.config;

import com.weighttracker.repository.UserRepository;
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.*;
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 UserDetailsService uds(UserRepository repo){
        return username -> repo.findByUsername(username)
            .map(u -> User.withUsername(u.getUsername())
                          .password(u.getPassword())
                          .roles(u.getRole())
                          .build())
            .orElseThrow(() -> new UsernameNotFoundException("Not found"));
    }

    @Bean
    public SecurityFilterChain filter(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(a -> a
                .requestMatchers("/css/**","/js/**","/images/**","/login","/login?error","/login?logout").permitAll()
                .requestMatchers("/usuarios/**").hasRole("ADMIN")
                .anyRequest().authenticated()
        )
        .formLogin(login -> login
                .loginPage("/login")
                .loginProcessingUrl("/do-login")
                .defaultSuccessUrl("/", true)
                .failureUrl("/login?error")
                .permitAll()
        )
        .logout(l -> l.logoutSuccessUrl("/login?logout").permitAll());
        return http.build();
    }

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