package com.zioinfo.mall.admin;

import com.zioinfo.mall.admin.dto.MallSetting;
import com.zioinfo.mall.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<MallSetting> list() {
        return mapper.findAll();
    }

    public MallSetting 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 필수");
        }
        MallSetting before = mapper.findByKey(key);
        mapper.upsert(key, value);
        String prev = before == null ? "(none)" : before.getValue();
        auditService.log("SETTING_CHANGE", key, prev + " -> " + value);
        return mapper.findByKey(key);
    }
}
