package com.zioinfo.kintex.system.role;

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/roles). ADMIN 게이트. */
@RestController
@RequestMapping("/api/admin/roles")
public class RoleController {

    private final RoleService service;
    private final SystemAccessGuard guard;

    public RoleController(RoleService service, SystemAccessGuard guard) {
        this.service = service;
        this.guard = guard;
    }

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

    @GetMapping("/permissions")
    public ApiResponse<List<PermissionDto>> permissions(@AuthenticationPrincipal KintexPrincipal principal) {
        guard.requireAdmin(principal);
        return ApiResponse.ok(service.permissions());
    }

    @Audited(action = "ROLE_SAVE", targetType = "sys_role")
    @PostMapping
    public ApiResponse<Void> save(@AuthenticationPrincipal KintexPrincipal principal,
                                  @Valid @RequestBody RoleDto role) {
        guard.requireAdmin(principal);
        service.save(role);
        return ApiResponse.ok(null);
    }

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