package link.at17.mid.tushare.web.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpSession;
import link.at17.mid.tushare.system.util.SpringContextHolder;
import link.at17.mid.tushare.web.models.WebUser;

@Service
public class AuthService implements UserDetailsService {
    
    public static final String LOGIN_USER = "loginUser";
    
    public static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT";

    public static final String CAPTCHA = "captcha";
    
    @Autowired
    HttpSession session;
    
    @Autowired
    WebUserService userService;
    
    public Boolean isLogin() {
        return session != null && session.getAttribute(SPRING_SECURITY_CONTEXT) != null;
    }

    public void setLogin(String username, String password) {
        AuthenticationManager authenticationManager = SpringContextHolder.getBean("authenticationManager");
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(username, password)
        );
        SecurityContextHolder.getContext().setAuthentication(authentication);
        session.setAttribute(SPRING_SECURITY_CONTEXT, SecurityContextHolder.getContext());
    }
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        
        WebUser user = userService.getOne(new LambdaQueryWrapper<WebUser>().eq(WebUser::getUsername, username));
        
        if (user != null) {
            return 
                User.withUsername(username)
                .password(user.getPassword())
                .roles("admin")
                .build();
        }
        throw new UsernameNotFoundException("用户不存在");
    }

}
