package com.example.demo.controller;

import com.example.demo.model.ApiResult;
import com.example.demo.model.Permission;
import com.example.demo.service.PermissionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 权限管理控制器。
 * <p>提供基于角色的权限分配、菜单权限、按钮权限、数据权限 RESTful API。</p>
 */
@Tag(name = "权限管理", description = "基于角色的权限分配、菜单权限、按钮权限、数据权限")
@RestController
@RequestMapping("/api/permission")
public class PermissionController {

    private final PermissionService permissionService;

    public PermissionController(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    /**
     * 为角色分配权限。
     *
     * @requirement(name="基于角色的权限分配", id="SRS-F-04-001")
     */
    @Operation(summary = "为角色分配权限")
    @PutMapping("/role")
    public ApiResult<Void> assignRole(
            @Parameter(description = "角色ID") @RequestParam Long roleId,
            @Parameter(description = "权限ID集合") @RequestBody Set<Long> permissionIds) {
        if (!permissionService.assignToRole(roleId, permissionIds)) {
            return ApiResult.error(400, "权限ID无效");
        }
        return ApiResult.success("权限分配成功", null);
    }

    /**
     * 获取菜单权限。
     *
     * @requirement(name="菜单权限", id="SRS-F-04-002")
     */
    @Operation(summary = "获取菜单权限")
    @GetMapping("/menu")
    public ApiResult<List<Permission>> getMenu(
            @Parameter(description = "角色ID集合") @RequestParam(required = false) Set<Long> roleIds) {
        return ApiResult.success(permissionService.getMenuPermissions(roleIds));
    }

    /**
     * 获取按钮权限。
     *
     * @requirement(name="按钮权限", id="SRS-F-04-003")
     */
    @Operation(summary = "获取按钮权限")
    @GetMapping("/button")
    public ApiResult<List<Permission>> getButton(
            @Parameter(description = "角色ID集合") @RequestParam(required = false) Set<Long> roleIds) {
        return ApiResult.success(permissionService.getButtonPermissions(roleIds));
    }

    /**
     * 获取数据权限。
     *
     * @requirement(name="数据权限分级管控", id="SRS-F-04-004")
     */
    @Operation(summary = "获取数据权限")
    @GetMapping("/data")
    public ApiResult<Map<String, Object>> getData(
            @Parameter(description = "角色ID") @RequestParam(required = false) Long roleId) {
        return ApiResult.success(permissionService.getDataPermission(roleId));
    }
}
