package tech.easyflow.system.options;

import com.mybatisflex.core.query.QueryWrapper;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.options.SysOptionStore;
import tech.easyflow.common.satoken.util.SaTokenUtil;
import tech.easyflow.common.util.StringUtil;
import tech.easyflow.common.web.exceptions.BusinessException;
import tech.easyflow.system.entity.SysOption;
import tech.easyflow.system.service.SysOptionService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigInteger;

@Component
public class DefaultOptionStore implements SysOptionStore {

    @Resource
    private SysOptionService optionService;


    @Override
    public void save(String key, Object value) {
        BigInteger tenantId = getTenantIdForWrite();
        if (value == null || !StringUtil.hasText(value.toString())) {
            optionService.remove(QueryWrapper.create()
                    .eq(SysOption::getTenantId, tenantId)
                    .eq(SysOption::getKey, key));
            return;
        }

        String newValue = value.toString().trim();
        SysOption option = optionService.getByOptionKey(key, tenantId);
        if (option == null) {
            option = new SysOption(key, newValue);
            option.setTenantId(tenantId);
            try {
                optionService.save(option);
            } catch (DuplicateKeyException e) {
                QueryWrapper queryWrapper = QueryWrapper.create()
                        .eq(SysOption::getTenantId, tenantId)
                        .eq(SysOption::getKey, key);
                optionService.update(option, queryWrapper);
            }
        } else {
            option.setValue(newValue);
            QueryWrapper queryWrapper = QueryWrapper.create()
                    .eq(SysOption::getTenantId, tenantId)
                    .eq(SysOption::getKey, key);
            optionService.update(option, queryWrapper);
        }
    }

    @Override
    public String get(String key) {
        BigInteger tenantId = getTenantIdForRead();
        if (tenantId == null) {
            return null;
        }
        SysOption option = optionService.getByOptionKey(key, tenantId);
        return option != null ? option.getValue() : null;
    }

    private BigInteger getTenantIdForWrite() {
        LoginAccount loginAccount = SaTokenUtil.getLoginAccount();
        if (loginAccount == null || loginAccount.getTenantId() == null) {
            throw new BusinessException("未获取到租户信息，无法保存系统配置");
        }
        return loginAccount.getTenantId();
    }

    private BigInteger getTenantIdForRead() {
        LoginAccount loginAccount = SaTokenUtil.getLoginAccount();
        return loginAccount != null ? loginAccount.getTenantId() : null;
    }
}
