package org.qinan.safetyeval.domain.service;

import org.qinan.safetyeval.domain.entity.AccountEntity;
import org.qinan.safetyeval.domain.exception.BizException;
import org.qinan.safetyeval.domain.exception.ErrorCode;
import org.qinan.safetyeval.domain.gateway.AccountGateway;
import org.qinan.safetyeval.domain.query.AccountQuery;
import org.qinan.safetyeval.domain.query.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 用户领域服务
 *
 * @author safety-eval
 */
@Service
public class AccountDomainService {

    @Resource
    private AccountGateway accountGateway;

    public AccountEntity add(AccountEntity entity) {
        assertAccountUnique(entity.getAccount(), null);
        return accountGateway.save(entity);
    }

    public AccountEntity get(Long id) {
        return accountGateway.get(id);
    }

    public AccountEntity modify(AccountEntity entity) {
        AccountEntity existing = accountGateway.get(entity.getId());
        if (existing == null) {
            throw new BizException(ErrorCode.ACCOUNT_NOT_FOUND);
        }
        assertAccountUnique(entity.getAccount(), entity.getId());
        return accountGateway.modify(entity);
    }

    public void delete(Long id) {
        AccountEntity existing = accountGateway.get(id);
        if (existing == null) {
            throw new BizException(ErrorCode.ACCOUNT_NOT_FOUND);
        }
        accountGateway.delete(id);
    }

    public PageResult<AccountEntity> page(AccountQuery query) {
        return accountGateway.page(query);
    }

    private void assertAccountUnique(String account, Long excludeId) {
        if (!StringUtils.hasText(account)) {
            return;
        }
        AccountEntity found = accountGateway.getByAccount(account);
        if (found != null && (excludeId == null || !excludeId.equals(found.getId()))) {
            throw new BizException(ErrorCode.ACCOUNT_EXISTS);
        }
    }

    public AccountEntity syncUserToGBS(String account) {
        AccountEntity found = accountGateway.getByAccount(account);
        if (Objects.isNull(found)) {
            throw new BizException(ErrorCode.ACCOUNT_NOT_FOUND);
        }
        return found;
    }
}
