package com.zioinfo.mall.admin;

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

import java.util.List;

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

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

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

    @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.role(), req.displayName()));
    }

    @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()));
    }

    @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. 감사 로그 (ADMIN/MANAGER) =====================

    @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<MallSetting>> settings() {
        return ApiResponse.ok(settingService.list());
    }

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

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

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