package com.erp.permission.controller;

import com.erp.common.core.model.ApiResponse;
import com.erp.permission.dto.*;
import com.erp.permission.service.PermissionService;
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/permissions")
@RequiredArgsConstructor
public class PermissionController {
    
    private final PermissionService permissionService;
    
    /**
     * 权限列表（支持分组和关键字过滤）
     */
    @GetMapping
    public ApiResponse<PermissionListResponse> listPermissions(
            @RequestParam(required = false) String group,
            @RequestParam(required = false) String keyword) {
        
        PermissionListResponse response = permissionService.listPermissions(group, keyword);
        return ApiResponse.success(response);
    }
    
    /**
     * 创建权限
     */
    @PostMapping
    public ApiResponse<PermissionDTO> createPermission(
            @Valid @RequestBody CreatePermissionRequest request) {
        
        PermissionDTO permission = permissionService.createPermission(request);
        return ApiResponse.success("权限创建成功", permission);
    }
    
    /**
     * 更新权限
     */
    @PutMapping("/{id}")
    public ApiResponse<PermissionDTO> updatePermission(
            @PathVariable Long id,
            @Valid @RequestBody UpdatePermissionRequest request) {
        
        PermissionDTO permission = permissionService.updatePermission(id, request);
        return ApiResponse.success("权限更新成功", permission);
    }
    
    /**
     * 删除权限
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deletePermission(@PathVariable Long id) {
        permissionService.deletePermission(id);
        return ApiResponse.<Void>success("删除成功", null);
    }
    
    /**
     * 获取所有权限分组
     */
    @GetMapping("/groups")
    public ApiResponse<List<String>> listGroups() {
        List<String> groups = permissionService.listGroups();
        return ApiResponse.success(groups);
    }
    
    /**
     * 批量创建权限
     */
    @PostMapping("/batch")
    public ApiResponse<BatchCreateResult> batchCreatePermissions(
            @Valid @RequestBody BatchCreatePermissionRequest request) {
        
        BatchCreateResult result = permissionService.batchCreatePermissions(request);
        return ApiResponse.success("成功创建 " + result.getCreated() + " 个权限", result);
    }
}
