package com.zioinfo.hrm.organization;

import com.zioinfo.hrm.common.ApiResponse;
import com.zioinfo.hrm.common.AuthSupport;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/hrm")
@RequiredArgsConstructor
public class OrgController {

    private final OrgService orgService;

    @GetMapping("/departments")
    public ApiResponse<List<Map<String, Object>>> departments() {
        return ApiResponse.ok(orgService.getDeptTree());
    }

    @PostMapping("/departments")
    public ApiResponse<Void> createDept(@RequestBody Map<String, Object> dept, Authentication auth) {
        AuthSupport.requireManager(auth);
        orgService.createDept(dept, AuthSupport.actor(auth));
        return ApiResponse.ok(null);
    }

    @PutMapping("/departments/{id}")
    public ApiResponse<Void> updateDept(@PathVariable Long id, @RequestBody Map<String, Object> dept, Authentication auth) {
        AuthSupport.requireManager(auth);
        dept.put("id", id);
        orgService.updateDept(dept);
        return ApiResponse.ok(null);
    }

    @DeleteMapping("/departments/{id}")
    public ApiResponse<Void> deleteDept(@PathVariable Long id, Authentication auth) {
        AuthSupport.requireManager(auth);
        orgService.deleteDept(id);
        return ApiResponse.ok(null);
    }

    @GetMapping("/positions")
    public ApiResponse<List<Map<String, Object>>> positions() {
        return ApiResponse.ok(orgService.getPositions());
    }

    @PostMapping("/positions")
    public ApiResponse<Void> createPosition(@RequestBody Map<String, Object> pos, Authentication auth) {
        AuthSupport.requireManager(auth);
        orgService.createPosition(pos);
        return ApiResponse.ok(null);
    }

    @GetMapping("/grades")
    public ApiResponse<List<Map<String, Object>>> grades() {
        return ApiResponse.ok(orgService.getGrades());
    }

    @PostMapping("/grades")
    public ApiResponse<Void> createGrade(@RequestBody Map<String, Object> grade, Authentication auth) {
        AuthSupport.requireManager(auth);
        orgService.createGrade(grade);
        return ApiResponse.ok(null);
    }
}
