package com.zioinfo.kintex.system.setting;

import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.common.audit.Audited;
import com.zioinfo.kintex.system.SystemAccessGuard;
import jakarta.validation.Valid;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** 시스템 설정 API (/api/admin/settings). ADMIN 게이트. 시크릿 값은 마스킹 응답. */
@RestController
@RequestMapping("/api/admin/settings")
public class SettingController {

    private final SettingService service;
    private final SystemAccessGuard guard;

    public SettingController(SettingService service, SystemAccessGuard guard) {
        this.service = service;
        this.guard = guard;
    }

    @GetMapping
    public ApiResponse<List<SettingDto>> list(@AuthenticationPrincipal KintexPrincipal principal) {
        guard.requireAdmin(principal);
        return ApiResponse.ok(service.list());
    }

    @GetMapping("/{key}")
    public ApiResponse<SettingDto> get(@AuthenticationPrincipal KintexPrincipal principal,
                                       @PathVariable String key) {
        guard.requireAdmin(principal);
        return ApiResponse.ok(service.get(key));
    }

    @Audited(action = "SETTING_SAVE", targetType = "sys_setting")
    @PostMapping
    public ApiResponse<Void> save(@AuthenticationPrincipal KintexPrincipal principal,
                                  @Valid @RequestBody SettingSaveRequest req) {
        guard.requireAdmin(principal);
        service.save(req, principal.userId());
        return ApiResponse.ok(null);
    }

    @Audited(action = "SETTING_DELETE", targetType = "sys_setting")
    @DeleteMapping("/{key}")
    public ApiResponse<Void> delete(@AuthenticationPrincipal KintexPrincipal principal,
                                    @PathVariable String key) {
        guard.requireAdmin(principal);
        service.delete(key);
        return ApiResponse.ok(null);
    }
}
