package com.zioinfo.kintex.system.setting;

import com.zioinfo.kintex.common.error.ApiException;
import com.zioinfo.kintex.common.error.ErrorCode;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 시스템 설정 조회/변경. secret_yn=Y 항목은 응답에서 값을 마스킹한다(계약 §0-3, 시크릿 미노출).
 * 시크릿 원문은 env 주입을 원칙으로 하며 DB 설정은 비-시크릿 운영값 위주.
 */
@Service
public class SettingService {

    private static final String MASK = "********";
    private final SettingMapper mapper;

    public SettingService(SettingMapper mapper) {
        this.mapper = mapper;
    }

    public List<SettingDto> list() {
        return mapper.findAll().stream().map(SettingService::toMaskedDto).toList();
    }

    public SettingDto get(String key) {
        Map<String, Object> r = mapper.findByKey(key);
        if (r == null) {
            throw new ApiException(ErrorCode.NOT_FOUND);
        }
        return toMaskedDto(r);
    }

    public void save(SettingSaveRequest req, String actorId) {
        Map<String, Object> p = new HashMap<>();
        p.put("settingKey", req.settingKey());
        p.put("settingValue", req.settingValue());
        p.put("valueType", req.valueType());
        p.put("description", req.description());
        p.put("secretYn", req.secretYn());
        p.put("updatedBy", actorId);
        mapper.upsert(p);
    }

    public void delete(String key) {
        mapper.delete(key);
    }

    private static SettingDto toMaskedDto(Map<String, Object> r) {
        String secretYn = str(r.get("secretYn"));
        String value = str(r.get("settingValue"));
        if ("Y".equals(secretYn) && value != null) {
            value = MASK;
        }
        return new SettingDto(str(r.get("settingKey")), value, str(r.get("valueType")),
                str(r.get("description")), secretYn);
    }
    private static String str(Object o) { return o == null ? null : String.valueOf(o); }
}
