package com.competition.modules.sys.controller;

import com.competition.common.result.PageResult;
import com.competition.common.result.Result;
import com.competition.common.util.SecurityUtil;
import com.competition.modules.sys.dto.CreateRoleDto;
import com.competition.modules.sys.dto.UpdateRoleDto;
import com.competition.modules.sys.service.ISysRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "角色管理")
@RestController
@RequestMapping("/roles")
@RequiredArgsConstructor
public class SysRoleController {

    private final ISysRoleService roleService;

    @PostMapping
    @Operation(summary = "创建角色")
    public Result<Map<String, Object>> create(@Valid @RequestBody CreateRoleDto dto) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(roleService.createRole(dto, tenantId));
    }

    @GetMapping
    @Operation(summary = "查询角色列表")
    public Result<PageResult<Map<String, Object>>> findAll(
            @RequestParam(defaultValue = "1") Long page,
            @RequestParam(defaultValue = "10") Long pageSize) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(roleService.findAll(page, pageSize, tenantId));
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询角色详情")
    public Result<Map<String, Object>> findOne(@PathVariable Long id) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(roleService.findDetail(id, tenantId));
    }

    @PatchMapping("/{id}")
    @Operation(summary = "更新角色")
    public Result<Map<String, Object>> update(@PathVariable Long id, @RequestBody UpdateRoleDto dto) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(roleService.updateRole(id, dto, tenantId));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除角色")
    public Result<Void> remove(@PathVariable Long id) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        roleService.removeRole(id, tenantId);
        return Result.success();
    }
}
