package cn.reghao.tnb.data.app.service;

import cn.reghao.tnb.data.app.model.po.UserProfile;
import cn.reghao.tnb.data.app.repository.UserProfileRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author reghao
 * @date 2025-05-29 11:31:18
 */
@Service
public class UserProfileService {
    private final UserProfileRepository userProfileRepository;

    public UserProfileService(UserProfileRepository userProfileRepository) {
        this.userProfileRepository = userProfileRepository;
    }

    public Mono<UserProfile> add(UserProfile userProfile) {
        return userProfileRepository.save(userProfile);
    }

    public Mono<ResponseEntity<UserProfile>> update(UserProfile userProfile) {
        return userProfileRepository.findById(userProfile.getId())
                .flatMap(userProfile1 -> userProfileRepository.save(userProfile))
                .map(userProfile1 -> new ResponseEntity<>(userProfile1, HttpStatus.OK))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    public Mono<ResponseEntity<Void>> delete(int id) {
        return userProfileRepository.findById(id)
                .flatMap(userProfile -> userProfileRepository.delete(userProfile).then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK))))
                .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    public Flux<UserProfile> find() {
        return userProfileRepository.findAll();
    }
}
