package com.zioinfo.hrm.organization;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OrgService {

    private final OrgMapper orgMapper;

    public List<Map<String, Object>> getDeptTree() {
        List<Map<String, Object>> all = orgMapper.findAllDepts();
        // 트리 구성: parentId가 null인 것이 루트
        Map<Object, List<Map<String, Object>>> byParent = all.stream()
            .collect(Collectors.groupingBy(d -> d.getOrDefault("parentId", 0L)));
        all.forEach(d -> d.put("children", byParent.getOrDefault(d.get("id"), new ArrayList<>())));
        return byParent.getOrDefault(0L, all.stream()
            .filter(d -> d.get("parentId") == null).collect(Collectors.toList()));
    }

    @Transactional
    public void createDept(Map<String, Object> dept, String actor) {
        dept.put("createdBy", actor);
        orgMapper.insertDept(dept);
    }

    @Transactional
    public void updateDept(Map<String, Object> dept) {
        orgMapper.updateDept(dept);
    }

    @Transactional
    public void deleteDept(Long id) {
        orgMapper.deleteDept(id);
    }

    public List<Map<String, Object>> getPositions() {
        return orgMapper.findAllPositions();
    }

    @Transactional
    public void createPosition(Map<String, Object> pos) {
        orgMapper.insertPosition(pos);
    }

    public List<Map<String, Object>> getGrades() {
        return orgMapper.findAllGrades();
    }

    @Transactional
    public void createGrade(Map<String, Object> grade) {
        orgMapper.insertGrade(grade);
    }
}
