package cn.novalon.gym.manage.sys.handler.permission;

import cn.novalon.gym.manage.sys.core.domain.SysPermission;
import cn.novalon.gym.manage.sys.core.service.ISysPermissionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 系统权限处理器
 * 
 * @author 张翔
 * @date 2026-03-25
 */
@Component
@Tag(name = "权限管理", description = "权限相关操作")
public class SysPermissionHandler {

    private final ISysPermissionService permissionService;

    public SysPermissionHandler(ISysPermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @Operation(summary = "获取所有权限", description = "获取系统中所有权限列表")
    public Mono<ServerResponse> getAllPermissions(ServerRequest request) {
        return ServerResponse.ok()
                .body(permissionService.findAll(), SysPermission.class);
    }

    @Operation(summary = "根据ID获取权限", description = "根据权限ID获取权限详细信息")
    public Mono<ServerResponse> getPermissionById(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));
        return permissionService.findById(id)
                .flatMap(permission -> ServerResponse.ok().bodyValue(permission))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    @Operation(summary = "检查权限编码是否存在", description = "检查指定权限编码是否已存在")
    public Mono<ServerResponse> checkCodeExists(ServerRequest request) {
        String code = request.queryParam("code").orElse(null);
        return permissionService.existsByPermissionCode(code)
                .flatMap(exists -> ServerResponse.ok().bodyValue(exists));
    }

    @Operation(summary = "获取权限总数", description = "获取系统中权限总数")
    public Mono<ServerResponse> getPermissionCount(ServerRequest request) {
        return permissionService.count()
                .flatMap(count -> ServerResponse.ok().bodyValue(count));
    }

    @Operation(summary = "根据权限编码获取权限", description = "根据权限编码获取权限详细信息")
    public Mono<ServerResponse> getPermissionByCode(ServerRequest request) {
        String code = request.pathVariable("code");
        return permissionService.findByPermissionCode(code)
                .flatMap(permission -> ServerResponse.ok().bodyValue(permission))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    @Operation(summary = "创建权限", description = "创建新权限")
    public Mono<ServerResponse> createPermission(ServerRequest request) {
        return request.bodyToMono(SysPermission.class)
                .flatMap(permissionService::createPermission)
                .flatMap(permission -> ServerResponse.status(HttpStatus.CREATED).bodyValue(permission));
    }

    @Operation(summary = "更新权限", description = "更新权限信息")
    public Mono<ServerResponse> updatePermission(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));
        return request.bodyToMono(SysPermission.class)
                .flatMap(permission -> {
                    permission.setId(id);
                    return permissionService.updatePermission(permission);
                })
                .flatMap(updatedPermission -> ServerResponse.ok().bodyValue(updatedPermission))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    @Operation(summary = "删除权限", description = "逻辑删除权限")
    public Mono<ServerResponse> deletePermission(ServerRequest request) {
        Long id = Long.valueOf(request.pathVariable("id"));
        return permissionService.deletePermission(id)
                .then(ServerResponse.ok().build())
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    @Operation(summary = "获取角色的权限", description = "根据角色ID获取该角色拥有的所有权限")
    public Mono<ServerResponse> getPermissionsByRoleId(ServerRequest request) {
        Long roleId = Long.valueOf(request.pathVariable("id"));
        return ServerResponse.ok()
                .body(permissionService.getPermissionsByRoleId(roleId), SysPermission.class);
    }

    @Operation(summary = "为角色分配权限", description = "为指定角色分配权限列表")
    public Mono<ServerResponse> assignPermissionsToRole(ServerRequest request) {
        Long roleId = Long.valueOf(request.pathVariable("id"));
        return request.bodyToMono(AssignPermissionsRequest.class)
                .flatMap(req -> permissionService.assignPermissionsToRole(roleId, req.permissionIds()))
                .then(ServerResponse.ok().build());
    }

    private record AssignPermissionsRequest(List<Long> permissionIds) {}
}