/* (C) 2023 YiRing, Inc. */
package com.yiring.auth.config;

import cn.dev33.satoken.stp.StpUtil;
import com.yiring.auth.domain.user.User;
import com.yiring.auth.domain.user.UserRepository;
import java.util.Optional;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;

/**
 * @author Jim
 * @version 0.1
 * 2023/3/3 11:43
 */

@Component
@Configurable
@RequiredArgsConstructor
public class InjectAuditorAware implements AuditorAware<String> {

    final UserRepository userRepository;

    @Override
    public @NonNull Optional<String> getCurrentAuditor() {
        if (StpUtil.isLogin()) {
            String loginId = StpUtil.getLoginIdAsString();
            Optional<User> optional = userRepository.findById(loginId);
            if (optional.isPresent()) {
                return Optional.of(optional.get().getId());
            }
        }

        return Optional.empty();
    }
}
