package com.eshore.gringotts.web.domain.confirmation.service;

import cn.hutool.core.util.ObjectUtil;
import com.eshore.gringotts.web.domain.base.service.SimpleServiceSupport;
import com.eshore.gringotts.web.domain.confirmation.entity.Confirmation;
import com.eshore.gringotts.web.domain.confirmation.repository.ConfirmationRepository;
import com.eshore.gringotts.web.domain.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author lanyuanxiaoyao
 * @date 2024-11-26
 */
@Slf4j
@Service
public class ConfirmationService extends SimpleServiceSupport<Confirmation> {
    private final ConfirmationRepository confirmationRepository;
    private final UserService userService;

    public ConfirmationService(ConfirmationRepository confirmationRepository, UserService userService) {
        super(confirmationRepository, userService);
        this.confirmationRepository = confirmationRepository;
        this.userService = userService;
    }

    @Override
    public Long save(Confirmation entity) {
        if (ObjectUtil.isNull(entity.getId()) && confirmationRepository.existsByTarget_Id(entity.getTarget().getId())) {
            throw new ConfirmationDuplicatedException();
        }
        return super.save(entity);
    }

    public void submit(Long id) {
        confirmationRepository.updateStateById(id, Confirmation.State.CHECKING, userService.currentLoginUser());
    }

    public void retract(Long id) {
        confirmationRepository.updateStateById(id, Confirmation.State.DRAFT, userService.currentLoginUser());
    }

    public static final class ConfirmationDuplicatedException extends RuntimeException {
        public ConfirmationDuplicatedException() {
            super("数据资源已绑定确权申请，无法再次申请");
        }
    }
}
