package incheon.uis.ums.web;

import incheon.com.security.util.SecurityUtil;
import incheon.uis.ums.service.UisCommonCodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;

@RestController
@RequestMapping("/api/uis/common")
@RequiredArgsConstructor
public class UisCommonController {

    private final UisCommonCodeService commonCodeService;

    @GetMapping("/code")
    public ResponseEntity<?> getCodeOptions(@RequestParam("listId") String listId) {
        SecurityUtil.requirePermission("UIS", "PERM_FUNC_READ");
        Map<String, Object> body = new HashMap<>();
        try {
            List<UisCommonCodeService.CodeOption> options = commonCodeService.getOptionsByListId(listId);
            body.put("success", true);
            body.put("options", options);
            return ResponseEntity.ok(body);
        } catch (RuntimeException e) {
            body.put("success", false);
            body.put("message", "공통코드 조회 중 오류가 발생했습니다.");
            return ResponseEntity.internalServerError().body(body);
        }
    }

    @GetMapping("/code/list")
    public ResponseEntity<?> getCodeOptionsByListIds(@RequestParam("listIds") List<String> listIds) {
        SecurityUtil.requirePermission("UIS", "PERM_FUNC_READ");
        Map<String, Object> body = new HashMap<>();
        try {
            List<UisCommonCodeService.CodeOption> options = commonCodeService.getOptionsByListIds(listIds);
            body.put("success", true);
            body.put("options", options);
            return ResponseEntity.ok(body);
        } catch (RuntimeException e) {
            body.put("success", false);
            body.put("message", "공통코드 조회 중 오류가 발생했습니다.");
            return ResponseEntity.internalServerError().body(body);
        }
    }
    
    @GetMapping("/code/layer/{layerId}")
    public ResponseEntity<?> getCodeOptionsByLayerId(@PathVariable("layerId") String layerId) {
        SecurityUtil.requirePermission("UIS", "PERM_FUNC_READ");
        Map<String, Object> body = new HashMap<>();
        try {
            List<UisCommonCodeService.CodeOptionLayer> options = commonCodeService.getOptionsByLayerId(layerId);
            // option 을 그룹화하여 반환 (table_name 별 그룹화, 테이블 그룹 내 column_name 별 그룹화)
            // 그룹화 키는 소문자로 변환하여 반환
            Map<String, Map<String, List<UisCommonCodeService.CodeOptionLayer>>> groupedOptions = options.stream()
                .collect(Collectors.groupingBy(o -> StringUtils.lowerCase(o.getTableName()),
                        Collectors.groupingBy(o -> StringUtils.lowerCase(o.getColumnName()))));
            body.put("success", true);
            body.put("options", groupedOptions);
            return ResponseEntity.ok(body);
        } catch (RuntimeException e) {
            body.put("success", false);
            body.put("message", "레이어 코드 조회 중 오류가 발생했습니다.");
            return ResponseEntity.internalServerError().body(body);
        }
    }
}


