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

import cn.novalon.gym.manage.auth.converter.UserConverter;
import cn.novalon.gym.manage.auth.dto.LoginRequest;
import cn.novalon.gym.manage.auth.dto.LoginResponse;
import cn.novalon.gym.manage.auth.dto.UserInfo;
import cn.novalon.gym.manage.auth.repository.AuthRepository;
import cn.novalon.gym.manage.auth.service.IAuthService;
import cn.novalon.gym.manage.auth.util.JwtUtil;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

@Service
public class AuthServiceImpl implements IAuthService {

    private final AuthRepository authRepository;
    private final JwtUtil jwtUtil;

    public AuthServiceImpl(AuthRepository authRepository, JwtUtil jwtUtil) {
        this.authRepository = authRepository;
        this.jwtUtil = jwtUtil;
    }

    @Override
    public Mono<LoginResponse> login(LoginRequest request) {
        return authRepository.validateLogin(request)
                .flatMap(user -> {
                    String accessToken = jwtUtil.generateToken(user.getId(), user.getUsername());
                    String refreshToken = jwtUtil.generateRefreshToken(user.getId(), user.getUsername());
                    
                    LoginResponse response = new LoginResponse();
                    response.setAccessToken(accessToken);
                    response.setRefreshToken(refreshToken);
                    response.setTokenType("Bearer");
                    response.setExpiresIn(7200L);
                    response.setUserInfo(UserConverter.toUserInfo(user));
                    
                    return Mono.just(response);
                });
    }

    @Override
    public Mono<UserInfo> getUserInfo(Long userId) {
        return authRepository.findById(userId)
                .map(UserConverter::toUserInfo)
                .switchIfEmpty(Mono.error(new RuntimeException("用户不存在")));
    }
}