package com.bizzan.bitrade.controller.system;

import com.bizzan.bitrade.controller.common.BaseAdminController;
import com.bizzan.bitrade.entity.SysConfig;
import com.bizzan.bitrade.service.SysConfigService;
import com.bizzan.bitrade.util.MessageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * 系统配置管理（kucoin库 sys_config 表，单条记录 id=1）
 */
@RestController
@RequestMapping("system/sys-config")
public class SysConfigController extends BaseAdminController {

    /** copy-trade-admin 跨服务读取该 key 做 maxPrincipalAmount 校验 */
    private static final String FOLLOW_SPECIAL_AMOUNT_KEY = "FOLLOW_SPECIAL_AMOUNT";

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping
    public MessageResult get() {
        SysConfig sysConfig = sysConfigService.get();
        if (sysConfig == null) {
            return error("sys_config 记录不存在");
        }
        syncFollowSpecialAmount(sysConfig.getFollowSpecialAmount());
        return success(sysConfig);
    }

    @PostMapping
    public MessageResult update(@RequestBody SysConfig sysConfig) {
        SysConfig saved = sysConfigService.save(sysConfig);
        syncFollowSpecialAmount(saved.getFollowSpecialAmount());
        return success("保存成功", saved);
    }

    private void syncFollowSpecialAmount(int value) {
        stringRedisTemplate.opsForValue().set(
                FOLLOW_SPECIAL_AMOUNT_KEY,
                String.valueOf(value)
        );
    }
}
