package org.dromara.system.service.impl;

import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.utils.MapstructUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.dromara.system.domain.SysAgreement;
import org.dromara.system.domain.bo.SysAgreementBo;
import org.dromara.system.domain.vo.SysAgreementVo;
import org.dromara.system.mapper.SysAgreementMapper;
import org.dromara.system.service.ISysAgreementService;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 协议信息 Service 业务层处理
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysAgreementServiceImpl implements ISysAgreementService {

    private final SysAgreementMapper baseMapper;

    /**
     * 根据ID查询协议，返回明文内容（走缓存）
     */
    @Cacheable(cacheNames = CacheNames.SYS_AGREEMENT, key = "#id")
    @Override
    public SysAgreementVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 修改协议：解码 base64 存库，刷新缓存并返回最新 VO
     */
    @CachePut(cacheNames = CacheNames.SYS_AGREEMENT, key = "#bo.id")
    @Override
    public SysAgreementVo updateByBo(SysAgreementBo bo) {
        SysAgreement update = MapstructUtils.convert(bo, SysAgreement.class);
        String decoded = new String(Base64.getDecoder().decode(bo.getContent()), StandardCharsets.UTF_8);
        update.setContent(decoded);
        baseMapper.updateById(update);
        return baseMapper.selectVoById(bo.getId());
    }

}
