package com.izouma.nineth.service;

import com.izouma.nineth.domain.IdentityAuth;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.AuthStatus;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.IdentityAuthRepo;
import com.izouma.nineth.repo.UserRepo;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class IdentityAuthService {

    private IdentityAuthRepo identityAuthRepo;
    private UserRepo         userRepo;
    private AdapayService    adapayService;

    public Page<IdentityAuth> all(PageQuery pageQuery) {
        return identityAuthRepo.findAll(JpaUtils.toSpecification(pageQuery, IdentityAuth.class), JpaUtils.toPageRequest(pageQuery));
    }

    public void apply(IdentityAuth identityAuth) {
        if (identityAuth.getUserId() == null) {
            throw new BusinessException("用户不存在");
        }
        User user = userRepo.findByIdAndDelFalse(identityAuth.getUserId()).orElseThrow(new BusinessException("用户不存在"));
        List<IdentityAuth> auths = identityAuthRepo.findByUserIdAndDelFalse(identityAuth.getUserId());
        auths.stream().filter(auth -> auth.getStatus() == AuthStatus.PENDING).findAny().ifPresent(a -> {
            throw new BusinessException("正在审核中，请勿重复提交");
        });
        auths.stream().filter(auth -> auth.getStatus() == AuthStatus.SUCCESS).findAny().ifPresent(a -> {
            throw new BusinessException("已认证，请勿重复提交");
        });
        identityAuth.setStatus(AuthStatus.PENDING);
        identityAuthRepo.save(identityAuth);
        user.setAuthStatus(AuthStatus.PENDING);
        userRepo.save(user);
    }

    public void audit(Long id, AuthStatus status) {
        IdentityAuth auth = identityAuthRepo.findByIdAndDelFalse(id).orElseThrow(new BusinessException("申请不存在"));
        if (auth.getStatus() != AuthStatus.PENDING) {
            throw new BusinessException("已经审核过");
        }
        User user = userRepo.findByIdAndDelFalse(auth.getUserId()).orElseThrow(new BusinessException("用户不存在"));
        if (status == AuthStatus.SUCCESS) {
            user.setAuthId(auth.getId());
        }
        auth.setStatus(status);
        identityAuthRepo.save(auth);
        user.setAuthStatus(status);
        userRepo.save(user);
    }
}
