package com.zioinfo.kintex.system.dept;

import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.common.audit.Audited;
import com.zioinfo.kintex.system.SystemAccessGuard;
import jakarta.validation.Valid;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** 시스템관리 — 조직(부서 트리) 관리 API. ADMIN 게이트. */
@RestController
@RequestMapping("/api/admin/depts")
public class DeptController {

    private final DeptService service;
    private final SystemAccessGuard guard;

    public DeptController(DeptService service, SystemAccessGuard guard) {
        this.service = service;
        this.guard = guard;
    }

    @GetMapping
    public ApiResponse<List<DeptDto>> tree(@AuthenticationPrincipal KintexPrincipal principal) {
        guard.requireAdmin(principal);
        return ApiResponse.ok(service.tree());
    }

    @Audited(action = "DEPT_SAVE", targetType = "dept")
    @PostMapping
    public ApiResponse<Void> save(@AuthenticationPrincipal KintexPrincipal principal,
                                  @Valid @RequestBody DeptSaveRequest req) {
        guard.requireAdmin(principal);
        service.save(req);
        return ApiResponse.ok(null);
    }

    @Audited(action = "DEPT_DELETE", targetType = "dept")
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@AuthenticationPrincipal KintexPrincipal principal,
                                    @PathVariable String id) {
        guard.requireAdmin(principal);
        service.delete(id);
        return ApiResponse.ok(null);
    }
}
