package com.lesingle.modules.sys.controller;

import com.lesingle.common.result.Result;
import com.lesingle.common.util.SecurityUtil;
import com.lesingle.modules.sys.dto.CreateMenuDto;
import com.lesingle.modules.sys.entity.SysMenu;
import com.lesingle.modules.sys.service.ISysMenuService;
import com.lesingle.modules.sys.service.ISysTenantService;
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.List;

@Tag(name = "菜单管理")
@RestController
@RequestMapping("/menus")
@RequiredArgsConstructor
public class SysMenuController {

    private final ISysMenuService menuService;
    private final ISysTenantService tenantService;

    @PostMapping
    @Operation(summary = "创建菜单")
    public Result<SysMenu> create(@Valid @RequestBody CreateMenuDto dto) {
        return Result.success(menuService.createMenu(dto));
    }

    @GetMapping
    @Operation(summary = "查询菜单列表（树形）")
    public Result<List<SysMenu>> findAll() {
        return Result.success(menuService.findAllTree());
    }

    @GetMapping("/user-menus")
    @Operation(summary = "获取当前用户菜单")
    public Result<List<SysMenu>> getUserMenus() {
        Long userId = SecurityUtil.getCurrentUserId();
        Long tenantId = SecurityUtil.getCurrentTenantId();
        boolean isSuperAdmin = SecurityUtil.isSuperAdmin() || tenantService.isSuperTenant(tenantId);
        return Result.success(menuService.getUserMenus(userId, tenantId, isSuperAdmin));
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询菜单详情")
    public Result<SysMenu> findOne(@PathVariable Long id) {
        return Result.success(menuService.findDetail(id));
    }

    @PatchMapping("/{id}")
    @Operation(summary = "更新菜单")
    public Result<SysMenu> update(@PathVariable Long id, @RequestBody CreateMenuDto dto) {
        return Result.success(menuService.updateMenu(id, dto));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除菜单")
    public Result<Void> remove(@PathVariable Long id) {
        menuService.removeMenu(id);
        return Result.success();
    }
}
