package com.hertz.modules.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hertz.common.api.ApiResponse;
import com.hertz.common.exception.BusinessException;
import com.hertz.security.SecurityUtils;
import com.hertz.modules.system.dto.MenuDto;
import com.hertz.modules.system.entity.SysMenu;
import com.hertz.modules.system.service.MenuService;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/system/menus")
public class MenuController {
  private final MenuService menuService;

  public MenuController(MenuService menuService) {
    this.menuService = menuService;
  }

  @GetMapping("/tree")
  public ApiResponse<List<MenuDto>> tree(Authentication authentication) {
    var userId = SecurityUtils.getCurrentUserId(authentication);
    if (userId == null) {
      throw new BusinessException(40100, "未登录或登录已过期");
    }
    return ApiResponse.ok(menuService.getMenuTreeByUserId(userId));
  }

  @GetMapping("/page")
  @PreAuthorize("hasRole('ADMIN') or hasAuthority('system:menu:view')")
  public ApiResponse<IPage<SysMenu>> page(
      @RequestParam(defaultValue = "1") int page,
      @RequestParam(defaultValue = "10") int size,
      @RequestParam(required = false) String keyword
  ) {
    return ApiResponse.ok(menuService.pageMenus(page, size, keyword));
  }

  @PostMapping
  @PreAuthorize("hasRole('ADMIN') or hasAuthority('system:menu:add')")
  public ApiResponse<Void> create(@RequestBody SysMenu menu) {
    menuService.saveMenu(menu);
    return ApiResponse.ok();
  }

  @PutMapping
  @PreAuthorize("hasRole('ADMIN') or hasAuthority('system:menu:edit')")
  public ApiResponse<Void> update(@RequestBody SysMenu menu) {
    menuService.updateMenu(menu);
    return ApiResponse.ok();
  }

  @DeleteMapping("/{id}")
  @PreAuthorize("hasRole('ADMIN') or hasAuthority('system:menu:remove')")
  public ApiResponse<Void> delete(@PathVariable("id") Long id) {
    menuService.deleteMenu(id);
    return ApiResponse.ok();
  }
}

