package cn.novalon.gym.manage.auth.repository.impl;

import cn.novalon.gym.manage.auth.converter.UserConverter;
import cn.novalon.gym.manage.auth.dao.UserDao;
import cn.novalon.gym.manage.auth.domain.User;
import cn.novalon.gym.manage.auth.dto.LoginRequest;
import cn.novalon.gym.manage.auth.repository.AuthRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@Component
public class AuthRepositoryImpl implements AuthRepository {

    private final UserDao userDao;
    private final PasswordEncoder passwordEncoder;

    public AuthRepositoryImpl(UserDao userDao, PasswordEncoder passwordEncoder) {
        this.userDao = userDao;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Mono<User> findByUsername(String username) {
        return userDao.findByUsername(username)
                .map(UserConverter::toDomain);
    }

    @Override
    public Mono<User> findById(Long id) {
        return userDao.findByIdAndDeletedAtIsNull(id)
                .map(UserConverter::toDomain);
    }

    @Override
    public Mono<User> validateLogin(LoginRequest request) {
        return userDao.findByUsername(request.getUsername())
                .flatMap(userEntity -> {
                    if (userEntity.getStatus() == 0) {
                        return Mono.error(new RuntimeException("用户已被禁用"));
                    }
                    if (passwordEncoder.matches(request.getPassword(), userEntity.getPassword())) {
                        return Mono.just(UserConverter.toDomain(userEntity));
                    } else {
                        return Mono.error(new RuntimeException("用户名或密码错误"));
                    }
                })
                .switchIfEmpty(Mono.error(new RuntimeException("用户名或密码错误")));
    }
}