package com.mosquito.project.permission;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门管理Controller - 部门CRUD API
 */
@RestController
@RequestMapping("/api/v1/departments")
public class DepartmentController {

    private final DepartmentService departmentService;

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

    /**
     * 获取部门列表
     */
    @GetMapping
    public ResponseEntity<List<SysDepartment>> list() {
        return ResponseEntity.ok(departmentService.findAll());
    }

    /**
     * 获取顶级部门列表
     */
    @GetMapping("/roots")
    public ResponseEntity<List<SysDepartment>> roots() {
        return ResponseEntity.ok(departmentService.findRootDepartments());
    }

    /**
     * 根据父部门ID获取子部门
     */
    @GetMapping("/children/{parentId}")
    public ResponseEntity<List<SysDepartment>> children(@PathVariable Long parentId) {
        return ResponseEntity.ok(departmentService.findByParentId(parentId));
    }

    /**
     * 根据ID获取部门
     */
    @GetMapping("/{id}")
    public ResponseEntity<SysDepartment> getById(@PathVariable Long id) {
        return departmentService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 创建部门
     */
    @PostMapping
    public ResponseEntity<SysDepartment> create(@RequestBody SysDepartment department) {
        try {
            SysDepartment saved = departmentService.save(department);
            return ResponseEntity.ok(saved);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 更新部门
     */
    @PutMapping("/{id}")
    public ResponseEntity<SysDepartment> update(@PathVariable Long id, @RequestBody SysDepartment department) {
        return departmentService.update(id, department)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 删除部门
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        try {
            departmentService.delete(id);
            return ResponseEntity.noContent().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }
}
