package com.zioinfo.esn.uiws.system.controller;

import com.zioinfo.esn.common.ApiResponse;
import com.zioinfo.esn.uiws.system.dto.DeptDto;
import com.zioinfo.esn.uiws.system.dto.DeptSaveDto;
import com.zioinfo.esn.uiws.system.dto.DeptTreeDto;
import com.zioinfo.esn.uiws.system.dto.PageResponse;
import com.zioinfo.esn.uiws.system.service.DeptService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** 2.3 부서(depts) — 목록/검색팝업/트리/CRUD. base: /api/system/depts */
@RestController
@RequestMapping("/api/system/depts")
@RequiredArgsConstructor
public class DeptController {

    private final DeptService deptService;

    @GetMapping
    public ApiResponse<PageResponse<DeptDto>> list(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        return ApiResponse.ok(deptService.list(keyword, page, size));
    }

    @GetMapping("/search")
    public ApiResponse<List<DeptDto>> search(@RequestParam(required = false) String keyword) {
        return ApiResponse.ok(deptService.searchPopup(keyword));
    }

    @GetMapping("/tree")
    public ApiResponse<List<DeptTreeDto>> tree() {
        return ApiResponse.ok(deptService.tree());
    }

    @PostMapping
    public ApiResponse<DeptDto> create(@Valid @RequestBody DeptSaveDto dto) {
        return ApiResponse.ok(deptService.create(dto));
    }

    @GetMapping("/{id}")
    public ApiResponse<DeptDto> get(@PathVariable("id") String id) {
        return ApiResponse.ok(deptService.get(id));
    }

    @PutMapping("/{id}")
    public ApiResponse<DeptDto> update(@PathVariable("id") String id, @Valid @RequestBody DeptSaveDto dto) {
        return ApiResponse.ok(deptService.update(id, dto));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable("id") String id) {
        deptService.delete(id);
        return ApiResponse.ok(null);
    }
}
