package com.lesingle.creation.controller;

import com.lesingle.creation.common.core.Result;
import com.lesingle.creation.common.security.UserPrincipal;
import com.lesingle.creation.dto.menu.CreateMenuDTO;
import com.lesingle.creation.dto.menu.UpdateMenuDTO;
import com.lesingle.creation.service.MenuService;
import com.lesingle.creation.vo.menu.MenuDetailVO;
import com.lesingle.creation.vo.menu.MenuTreeVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单管理控制器
 */
@Tag(name = "菜单管理")
@RestController
@RequestMapping("/api/menus")
@RequiredArgsConstructor
public class MenuController {

    private final MenuService menuService;

    @PostMapping
    @Operation(summary = "创建菜单")
    @PreAuthorize("hasAuthority('menu:create')")
    public Result<MenuDetailVO> create(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestBody @Validated CreateMenuDTO dto) {
        Long operatorId = userPrincipal.getUserId();
        MenuDetailVO result = menuService.create(dto, operatorId);
        return Result.success(result);
    }

    @GetMapping
    @Operation(summary = "菜单树")
    @PreAuthorize("hasAuthority('menu:read')")
    public Result<List<MenuTreeVO>> tree() {
        List<MenuTreeVO> result = menuService.tree();
        return Result.success(result);
    }

    @GetMapping("/user-menus")
    @Operation(summary = "当前用户菜单")
    @PreAuthorize("hasAuthority('menu:read')")
    public Result<List<MenuTreeVO>> userMenus(
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Long userId = userPrincipal.getUserId();
        Long tenantId = userPrincipal.getTenantId();
        List<MenuTreeVO> result = menuService.getUserMenus(userId, tenantId);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "菜单详情")
    @PreAuthorize("hasAuthority('menu:read')")
    public Result<MenuDetailVO> detail(@PathVariable Long id) {
        MenuDetailVO result = menuService.detail(id);
        return Result.success(result);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新菜单")
    @PreAuthorize("hasAuthority('menu:update')")
    public Result<MenuDetailVO> update(
            @PathVariable Long id,
            @RequestBody @Validated UpdateMenuDTO dto) {
        MenuDetailVO result = menuService.update(id, dto);
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除菜单")
    @PreAuthorize("hasAuthority('menu:delete')")
    public Result<Void> delete(@PathVariable Long id) {
        menuService.delete(id);
        return Result.success();
    }
}
