package com.erp.permission.controller;

import com.erp.common.core.model.ApiResponse;
import com.erp.permission.dto.*;
import com.erp.permission.service.RoleService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/roles")
@RequiredArgsConstructor
public class RoleController {
    
    private final RoleService roleService;
    
    /**
     * 角色列表
     */
    @GetMapping
    public ApiResponse<RoleListResponse> listRoles(
            @RequestParam(required = false) String keyword) {
        
        RoleListResponse response = roleService.listRoles(keyword);
        return ApiResponse.success(response);
    }
    
    /**
     * 创建角色
     */
    @PostMapping
    public ApiResponse<RoleDTO> createRole(
            @Valid @RequestBody CreateRoleRequest request) {
        
        RoleDTO role = roleService.createRole(request);
        return ApiResponse.success("角色创建成功", role);
    }
    
    /**
     * 更新角色
     */
    @PutMapping("/{id}")
    public ApiResponse<RoleDTO> updateRole(
            @PathVariable Long id,
            @Valid @RequestBody UpdateRoleRequest request) {
        
        RoleDTO role = roleService.updateRole(id, request);
        return ApiResponse.success("角色更新成功", role);
    }
    
    /**
     * 删除角色
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteRole(@PathVariable Long id) {
        roleService.deleteRole(id);
        return ApiResponse.<Void>success("删除成功", null);
    }
    
    /**
     * 获取角色权限列表
     */
    @GetMapping("/{id}/permissions")
    public ApiResponse<List<String>> getRolePermissions(@PathVariable Long id) {
        List<String> permissions = roleService.getRolePermissions(id);
        return ApiResponse.success(permissions);
    }
    
    /**
     * 分配角色权限
     */
    @PutMapping("/{id}/permissions")
    public ApiResponse<Void> assignPermissions(
            @PathVariable Long id,
            @Valid @RequestBody AssignPermissionsRequest request) {
        
        roleService.assignPermissions(id, request);
        return ApiResponse.<Void>success("权限分配成功", null);
    }
}
