package com.toyshop.service;

import com.toyshop.dto.AuthRequest;
import com.toyshop.dto.RegisterRequest;
import com.toyshop.entity.User;
import com.toyshop.entity.UserRole;
import com.toyshop.repository.UserRepository;
import com.toyshop.security.JwtTokenProvider;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AuthService {
  private final UserRepository userRepository;
  private final PasswordEncoder passwordEncoder;
  private final AuthenticationManager authenticationManager;
  private final JwtTokenProvider jwtTokenProvider;

  public AuthService(UserRepository userRepository, PasswordEncoder passwordEncoder,
                     AuthenticationManager authenticationManager, JwtTokenProvider jwtTokenProvider) {
    this.userRepository = userRepository;
    this.passwordEncoder = passwordEncoder;
    this.authenticationManager = authenticationManager;
    this.jwtTokenProvider = jwtTokenProvider;
  }

  public String register(RegisterRequest request) {
    if (userRepository.findByUsername(request.getUsername()).isPresent()) {
      throw new IllegalArgumentException("用户名已存在");
    }
    User user = new User();
    user.setUsername(request.getUsername());
    user.setPassword(passwordEncoder.encode(request.getPassword()));
    user.setPhone(request.getPhone());
    user.setEmail(request.getEmail());
    user.setRole(UserRole.USER);
    userRepository.save(user);
    return jwtTokenProvider.generateToken(user.getUsername(), user.getRole().name());
  }

  public String login(AuthRequest request) {
    Authentication authentication = authenticationManager.authenticate(
        new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
    var userDetails = (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
    var user = userRepository.findByUsername(userDetails.getUsername()).orElseThrow();
    return jwtTokenProvider.generateToken(user.getUsername(), user.getRole().name());
  }
}
