package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.entity.dto.RoleQueryDTO;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.Role;
import com.haha.service.RoleService;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理控制器
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/role")
public class RoleController {

    private final RoleService roleService;
    
    /**
     * 分页查询角色列表
     */
    @RequirePermission("role:read")
    @PostMapping
    public Result<PageResult<Role>> list(@RequestBody RoleQueryDTO queryDTO) {
        queryDTO.validate();
        
        Result<IPage<Role>> result = roleService.getRoleList(
                queryDTO.getPage(),
                queryDTO.getPageSize(),
                queryDTO.getName(),
                queryDTO.getCode()
        );
        
        if (result.getCode() == 200 && result.getData() != null) {
            return Result.success("查询成功", PageResult.of(result.getData()));
        }
        return Result.error(result.getCode(), "查询失败");
    }
    
    /**
     * 获取所有角色(不分页)
     */
    @RequirePermission("role:read")
    @GetMapping("/list-all-role")
    public Result<List<Role>> listAll() {
        return roleService.getAllRoles();
    }
    
    /**
     * 添加角色
     */
    @RequirePermission("role:create")
    @Log(module = "角色管理", operation = OperationType.INSERT, summary = "添加角色")
    @PostMapping("/add")
    public Result<Void> add(@RequestBody Role role) {
        return roleService.addRole(role);
    }
    
    /**
     * 更新角色
     */
    @RequirePermission("role:update")
    @Log(module = "角色管理", operation = OperationType.UPDATE, summary = "更新角色")
    @PostMapping("/update")
    public Result<Void> update(@RequestBody Role role) {
        return roleService.updateRole(role);
    }
    
    /**
     * 删除角色
     */
    @RequirePermission("role:delete")
    @Log(module = "角色管理", operation = OperationType.DELETE, summary = "删除角色")
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        return roleService.deleteRole(id);
    }
}
