package incheon.ags.uis.code.web;

import incheon.ags.uis.code.service.CodeGroupService;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/v1/code/group")
public class CodeGroupApiController {

    private final CodeGroupService codeGroupService;

    public CodeGroupApiController(CodeGroupService codeGroupService) {
        this.codeGroupService = codeGroupService;
    }

    @DeleteMapping("/{groupCd}")
    public ResponseEntity<Map<String, Object>> deleteGroup(@PathVariable String groupCd) {
        Map<String, Object> body = new HashMap<>();

        if (groupCd == null || groupCd.isBlank()) {
            body.put("success", false);
            body.put("message", "그룹코드가 없습니다.");
            return ResponseEntity.badRequest().body(body);
        }

        try {
            codeGroupService.deleteCodeGroup(groupCd);
            body.put("success", true);
            body.put("message", "그룹코드가 정상적으로 삭제되었습니다.");
        } catch (DataIntegrityViolationException e) {
            log.warn("그룹코드 삭제 실패 - 참조 데이터 존재: groupCd={}", groupCd, e);
            body.put("success", false);
            body.put("message", "해당 그룹코드를 사용하는 데이터가 존재하여 삭제할 수 없습니다.");
            return ResponseEntity.badRequest().body(body);
        } catch (Exception e) {
            log.error("그룹코드 삭제 중 예상치 못한 오류 발생: groupCd={}", groupCd, e);
            body.put("success", false);
            body.put("message", "그룹코드 삭제 중 오류가 발생했습니다.");
            return ResponseEntity.internalServerError().body(body);
        }

        return ResponseEntity.ok(body);
    }
}

