package com.agent.management.controller;

import com.agent.management.common.Result;
import com.agent.management.model.vo.CategoryVO;
import com.agent.management.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/categories")
@RequiredArgsConstructor
public class CategoryController {

    private final CategoryService categoryService;

    @GetMapping
    public Result<List<CategoryVO>> getCategoryTree() {
        return Result.success(categoryService.getCategoryTree());
    }

    @PostMapping
    public Result<CategoryVO> createCategory(@RequestBody Map<String, Object> body) {
        Long parentId = body.get("parentId") != null ? Long.valueOf(body.get("parentId").toString()) : null;
        String name = (String) body.get("name");
        return Result.success(categoryService.createCategory(parentId, name));
    }

    @PutMapping("/{id}")
    public Result<CategoryVO> updateCategory(@PathVariable Long id,
                                              @RequestBody Map<String, String> body) {
        return Result.success(categoryService.updateCategory(id, body.get("name")));
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteCategory(@PathVariable Long id) {
        categoryService.deleteCategory(id);
        return Result.success("删除成功", null);
    }

    @PutMapping("/{id}/move")
    public Result<Void> moveCategory(@PathVariable Long id,
                                      @RequestBody Map<String, Object> body) {
        Long newParentId = body.get("parentId") != null ? Long.valueOf(body.get("parentId").toString()) : null;
        categoryService.moveCategory(id, newParentId);
        return Result.success("移动成功", null);
    }
}
