package com.example.demo.controller;

import com.example.demo.model.ApiResult;
import com.example.demo.model.Department;
import com.example.demo.service.DepartmentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门管理控制器。
 * <p>提供部门的新增、编辑、删除、树形结构查询 RESTful API。</p>
 */
@Tag(name = "部门管理", description = "部门的新增、编辑、删除、树形结构查询")
@RestController
@RequestMapping("/api/dept")
public class DepartmentController {

    private final DepartmentService departmentService;

    public DepartmentController(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    /**
     * 新增部门。
     *
     * @requirement(name="部门管理", id="SRS-F-01-003")
     * @param dept 部门信息
     * @return 操作结果
     */
    @Operation(summary = "新增部门")
    @PostMapping("/add")
    public ApiResult<Department> add(@RequestBody Department dept) {
        return ApiResult.success("新增成功", departmentService.save(dept));
    }

    /**
     * 编辑部门。
     *
     * @requirement(name="部门管理", id="SRS-F-01-003")
     * @param dept 部门信息
     * @return 操作结果
     */
    @Operation(summary = "编辑部门")
    @PutMapping("/edit")
    public ApiResult<Department> edit(@RequestBody Department dept) {
        Department updated = departmentService.update(dept);
        if (updated == null) {
            return ApiResult.error(404, "部门不存在");
        }
        return ApiResult.success("编辑成功", updated);
    }

    /**
     * 删除部门。
     *
     * @requirement(name="部门管理", id="SRS-F-01-003")
     * @param id 部门ID
     * @return 操作结果
     */
    @Operation(summary = "删除部门")
    @DeleteMapping("/delete/{id}")
    public ApiResult<Void> delete(@PathVariable Long id) {
        if (!departmentService.deleteById(id)) {
            return ApiResult.error(400, "部门不存在或存在子部门无法删除");
        }
        return ApiResult.success("删除成功", null);
    }

    /**
     * 查询部门树。
     *
     * @requirement(name="部门管理", id="SRS-F-01-003")
     * @return 树形部门列表
     */
    @Operation(summary = "查询部门树")
    @GetMapping("/tree")
    public ApiResult<List<Department>> tree() {
        return ApiResult.success(departmentService.tree());
    }
}
