package com.zioinfo.cms.admin;

import com.zioinfo.cms.admin.dto.AuditLog;
import com.zioinfo.cms.admin.dto.CmsSetting;
import com.zioinfo.cms.admin.dto.UserDto;
import com.zioinfo.cms.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * GUARDiA CMS 관리자 API.
 *
 * <p>RBAC(SecurityConfig requestMatchers 로 통제):
 * <ul>
 *   <li>/api/admin/users/**    — SUPERADMIN</li>
 *   <li>/api/admin/audit       — SUPERADMIN, EDITOR</li>
 *   <li>/api/admin/settings    — GET: SUPERADMIN/EDITOR, PUT: SUPERADMIN</li>
 * </ul>
 */
@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminController {

    private final AdminUserService userService;
    private final AuditService auditService;
    private final SettingService settingService;

    // ===================== 1. 사용자 관리 (SUPERADMIN) =====================

    @GetMapping("/users")
    public ApiResponse<List<UserDto>> listUsers() {
        return ApiResponse.ok(userService.list());
    }

    @PostMapping("/users")
    public ApiResponse<UserDto> createUser(@RequestBody CreateUserRequest req) {
        return ApiResponse.ok(userService.create(req.username(), req.password(), req.displayName(), req.role()));
    }

    @PutMapping("/users/{id}/role")
    public ApiResponse<UserDto> updateRole(@PathVariable Long id, @RequestBody RoleRequest req) {
        return ApiResponse.ok(userService.updateRole(id, req.role()));
    }

    @PutMapping("/users/{id}/active")
    public ApiResponse<UserDto> updateActive(@PathVariable Long id, @RequestBody ActiveRequest req) {
        return ApiResponse.ok(userService.updateActive(id, req.active()));
    }

    @PutMapping("/users/{id}/password")
    public ApiResponse<UserDto> resetPassword(@PathVariable Long id, @RequestBody PasswordRequest req) {
        return ApiResponse.ok(userService.resetPassword(id, req.password()));
    }

    /** 관리자 OTP 초기화(사용자 관리 화면 버튼) — OTP 시크릿 NULL → 다음 로그인 시 QR 재등록 유도. */
    @PostMapping("/users/{id}/otp-reset")
    public ApiResponse<UserDto> resetOtp(@PathVariable Long id) {
        return ApiResponse.ok(userService.resetOtp(id));
    }

    @DeleteMapping("/users/{id}")
    public ApiResponse<Void> deleteUser(@PathVariable Long id, Authentication auth) {
        String currentUsername = auth != null ? auth.getName() : null;
        userService.delete(id, currentUsername);
        return ApiResponse.ok(null);
    }

    // ===================== 2. 감사 로그 (SUPERADMIN/EDITOR) =====================

    @GetMapping("/audit")
    public ApiResponse<List<AuditLog>> audit(
            @RequestParam(value = "action", required = false) String action,
            @RequestParam(value = "actor", required = false) String actor,
            @RequestParam(value = "limit", defaultValue = "100") int limit) {
        return ApiResponse.ok(auditService.find(action, actor, limit));
    }

    // ===================== 3. 시스템 설정 =====================

    @GetMapping("/settings")
    public ApiResponse<List<CmsSetting>> settings() {
        return ApiResponse.ok(settingService.list());
    }

    @PutMapping("/settings/{key}")
    public ApiResponse<CmsSetting> updateSetting(@PathVariable String key,
                                                 @RequestBody SettingRequest req) {
        return ApiResponse.ok(settingService.update(key, req.value()));
    }

    // ===================== 요청 DTO =====================

    record CreateUserRequest(String username, String password, String displayName, String role) {}
    record RoleRequest(String role) {}
    record ActiveRequest(boolean active) {}
    record PasswordRequest(String password) {}
    record SettingRequest(String value) {}
}
