package com.agent.management.controller;

import com.agent.management.common.Result;
import com.agent.management.config.KbProperties;
import com.agent.management.model.entity.KbCategory;
import com.agent.management.service.KbCategoryService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 知识库分类管理 API
 */
@RestController
@RequestMapping("/api/kb/categories")
@RequiredArgsConstructor
public class KbCategoryController {

    private final KbCategoryService categoryService;
    private final KbProperties kbProps;

    /**
     * 知识库总开关状态（前端据此提示用户）
     */
    @GetMapping("/_status")
    public Result<StatusVO> status() {
        StatusVO vo = new StatusVO();
        vo.setEnabled(kbProps.isEnabled());
        return Result.success(vo);
    }

    @GetMapping
    public Result<List<KbCategory>> list(@RequestParam(required = false) Long parentId) {
        List<KbCategory> data = parentId != null
                ? categoryService.listChildren(parentId)
                : categoryService.listAll();
        return Result.success(data);
    }

    @GetMapping("/{id}")
    public Result<KbCategory> get(@PathVariable Long id) {
        return Result.success(categoryService.get(id));
    }

    @PostMapping
    public Result<KbCategory> create(@RequestBody CategoryReq req) {
        return Result.success(categoryService.create(req.getParentId(), req.getName()));
    }

    @PutMapping("/{id}")
    public Result<KbCategory> update(@PathVariable Long id, @RequestBody CategoryReq req) {
        return Result.success(categoryService.update(id, req.getName(), req.getParentId(), req.getSortOrder()));
    }

    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        categoryService.delete(id);
        return Result.success(null);
    }

    @Data
    public static class CategoryReq {
        private String name;
        private Long parentId;
        private Integer sortOrder;
    }

    @Data
    public static class StatusVO {
        private boolean enabled;
    }
}
