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.CreatePermissionDto;
import com.competition.modules.sys.entity.SysPermission;
import com.competition.modules.sys.service.ISysPermissionService;
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.*;

@Tag(name = "权限管理")
@RestController
@RequestMapping("/permissions")
@RequiredArgsConstructor
public class SysPermissionController {

    private final ISysPermissionService permissionService;

    @PostMapping
    @Operation(summary = "创建权限")
    public Result<SysPermission> create(@Valid @RequestBody CreatePermissionDto dto) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(permissionService.createPermission(dto, tenantId));
    }

    @GetMapping
    @Operation(summary = "查询权限列表")
    public Result<PageResult<SysPermission>> findAll(
            @RequestParam(defaultValue = "1") Long page,
            @RequestParam(defaultValue = "10") Long pageSize) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(permissionService.findAll(page, pageSize, tenantId));
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询权限详情")
    public Result<SysPermission> findOne(@PathVariable Long id) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(permissionService.findDetail(id, tenantId));
    }

    @PatchMapping("/{id}")
    @Operation(summary = "更新权限")
    public Result<SysPermission> update(@PathVariable Long id, @RequestBody CreatePermissionDto dto) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(permissionService.updatePermission(id, dto, tenantId));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除权限")
    public Result<Void> remove(@PathVariable Long id) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        permissionService.removePermission(id, tenantId);
        return Result.success();
    }
}
