package com.zioinfo.esn.admin;

import com.zioinfo.esn.admin.dto.EsnSetting;
import com.zioinfo.esn.admin.mapper.SettingMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 시스템 설정 서비스.
 *
 * <p>조회는 ADMIN/MANAGER, 변경은 ADMIN (SecurityConfig requestMatchers 로 통제).
 * 변경 시 감사 로그에 이전→이후 요약을 기록한다(값은 민감하지 않은 운영 설정만 다룬다).
 */
@Service
@RequiredArgsConstructor
public class SettingService {

    private final SettingMapper mapper;
    private final AuditService auditService;

    public List<EsnSetting> list(String category) {
        return mapper.findAll(category);
    }

    public EsnSetting update(String key, String value) {
        if (key == null || key.isBlank()) {
            throw new IllegalArgumentException("ERR-SET-400: key 필수");
        }
        if (value == null) {
            throw new IllegalArgumentException("ERR-SET-400: value 필수");
        }
        EsnSetting before = mapper.findByKey(key);
        String category = before == null ? "GENERAL" : before.getCategory();
        String description = before == null ? null : before.getDescription();
        mapper.upsert(key, value, category, description);
        String prev = before == null ? "(none)" : before.getSettingValue();
        auditService.log(null, "SETTING_CHANGE", "SETTING", key,
                prev + " -> " + value, true);
        return mapper.findByKey(key);
    }
}
