package com.test.bijihoudaun.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.bijihoudaun.bo.UpdatePasswordBo;
import com.test.bijihoudaun.common.exception.BusinessException;
import com.test.bijihoudaun.common.exception.RegistrationException;
import com.test.bijihoudaun.entity.User;
import com.test.bijihoudaun.mapper.UserMapper;
import com.test.bijihoudaun.service.UserService;
import com.test.bijihoudaun.util.JwtTokenUtil;
import com.test.bijihoudaun.util.PasswordUtils;
import com.test.bijihoudaun.util.UuidV7;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
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 org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUsername(username);
        if (ObjectUtil.isNull(user)) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>()); // 账号，密码，权限
    }

    @Override
    public User register(String username, String password, String email) {
        String encrypt = PasswordUtils.encrypt(password);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        if (this.count(queryWrapper) > 0) {
            throw new RegistrationException("用户名已存在");
        }
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, email);
        if (this.count(queryWrapper) > 0) {
            throw new RegistrationException("电子邮箱已被注册");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(encrypt);
        user.setEmail(email);
        // user.setCreatedAt(new Date()); // Let the database handle the default value
        userMapper.insert(user);
        return user;
    }

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public String login(String username, String password) {
        UserDetails userDetails = loadUserByUsername(username);
        if (!PasswordUtils.verify(password, userDetails.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        return jwtTokenUtil.generateToken(userDetails);
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public Boolean isTokenExpired(Long id, String token) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, id)
                .eq(User::getToken, token);
        User user = getOne(queryWrapper);
        // 修改过期检查逻辑
        return ObjectUtil.isNotNull(user) && new Date().before(user.getTokenEnddata());
    }

    @Override
    public void updatePassword(Long userId, UpdatePasswordBo updatePasswordBo) {
        User user = getById(userId);
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException("用户不存在");
        }
        if (!PasswordUtils.verify(updatePasswordBo.getOldPassword(), user.getPassword())) {
            throw new BusinessException("旧密码不正确");
        }
        String newPassword = PasswordUtils.encrypt(updatePasswordBo.getNewPassword());
        user.setPassword(newPassword);
        updateById(user);
    }
}