package incheon.ags.ias.dept.web;

import incheon.ags.ias.dept.service.DeptService;
import incheon.ags.ias.dept.vo.DeptSearchVO;
import incheon.ags.ias.dept.vo.DeptVO;
import incheon.ags.ias.dept.web.dto.DeptRequestDTO;
import incheon.com.cmm.api.DefaultApiResponse;
import incheon.com.cmm.context.RequestContext;
import incheon.com.cmm.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

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

@RestController
@RequiredArgsConstructor
@Slf4j
public class DeptApiController {
    private final DeptService deptService;

    /**
     * 부서 목록 조회 API (페이징 지원)
     * GET /api/v1/dept/list
     */
    @GetMapping("/api/v1/dept/list")
    public ResponseEntity<DefaultApiResponse<Map<String, Object>>> getDeptList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int recordCountPerPage,
            @RequestParam(required = false) String searchKeyword) throws Exception {

        log.debug("부서 목록 조회 - page: {}, recordCountPerPage: {}, searchKeyword: {}", page, recordCountPerPage, searchKeyword);

        DeptSearchVO searchVO = new DeptSearchVO();
        searchVO.setSearchKeyword(searchKeyword);

        // 1. 총 개수 조회
        int totalCount = deptService.selectDeptCnt(searchVO);

        // 2. PaginationInfo 설정
        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setCurrentPageNo(page);
        paginationInfo.setRecordCountPerPage(recordCountPerPage);
        paginationInfo.setPageSize(searchVO.getPageSize());  // 기본값 10
        paginationInfo.setTotalRecordCount(totalCount);

        // 3. 페이징 파라미터 설정 (firstIndex 계산)
        searchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
        searchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

        // 4. 데이터 조회
        List<Map<String, Object>> list = deptService.selectDeptList(searchVO);

        // 5. 응답 구성
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", list);
        resultMap.put("paginationInfo", paginationInfo);
        resultMap.put("totalCount", totalCount);

        return ResponseEntity.ok(DefaultApiResponse.success(resultMap));
    }

    @PostMapping("/ags/ias/dept/deptRegistAction.do")
    public ResponseEntity<DefaultApiResponse<DeptVO>> deptRegistAction(
            @RequestBody DeptRequestDTO deptRequestDTO) throws Exception {

        log.info("부서 등록 요청: {}", deptRequestDTO.toString());

        // 현재 접속한 사용자 ID 설정
        String loginUserId = RequestContext.getCurrentUserId();


        DeptVO deptVO = deptRequestDTO.toEntity();
        deptVO.setDeptCd(null); // DB selectKey에서 자동 생성되도록 함
        deptVO.setFrstRegId(loginUserId);
        deptVO.setLastMdfcnId(loginUserId);

        int result = deptService.insertDept(deptVO);

        if (result <= 0) {
            throw new BusinessException("부서 등록에 실패했습니다.");
        }

        log.info("부서 등록 성공 - 부서코드: {}", deptVO.getDeptCd());
        return ResponseEntity.ok(
            DefaultApiResponse.success(deptVO, "부서가 성공적으로 등록되었습니다.")
        );
    }

    @PutMapping("/ags/ias/dept/deptModifyAction.do/{deptCd}")
    public ResponseEntity<DefaultApiResponse<DeptVO>> deptModifyAction(
            @PathVariable("deptCd") String deptCd,
            @RequestBody DeptRequestDTO deptRequestDTO) throws Exception {

        log.info("부서 수정 요청 - 부서코드: {}, 데이터: {}", deptCd, deptRequestDTO.toString());

        if (deptCd == null || deptCd.trim().isEmpty()) {
            throw new BusinessException("수정할 부서 코드가 없습니다.");
        }

        // 현재 접속한 사용자 ID 설정
        String loginUserId = RequestContext.getCurrentUserId();


        DeptVO deptVO = deptRequestDTO.toEntity();
        deptVO.setDeptCd(deptCd);
        deptVO.setLastMdfcnId(loginUserId);

        // 부서 존재 여부 확인
        DeptVO existingDept = new DeptVO();
        existingDept.setDeptCd(deptCd);
        DeptVO foundDept = deptService.selectDeptDetail(existingDept);

        if (foundDept == null) {
            throw new BusinessException("수정할 부서를 찾을 수 없습니다.");
        }

        int result = deptService.updateDept(deptVO);

        if (result <= 0) {
            throw new BusinessException("부서 수정에 실패했습니다.");
        }

        log.info("부서 수정 성공 - 부서코드: {}", deptCd);
        return ResponseEntity.ok(
            DefaultApiResponse.success(deptVO, "부서가 성공적으로 수정되었습니다.")
        );
    }

    @DeleteMapping("/ags/ias/dept/deptDeleteAction.do/{deptCd}")
    public ResponseEntity<DefaultApiResponse<Object>> deptDeleteAction(
            @PathVariable("deptCd") String deptCd) throws Exception {

        log.info("부서 삭제 요청 - 부서코드: {}", deptCd);

        if (deptCd == null || deptCd.trim().isEmpty()) {
            throw new BusinessException("삭제할 부서 코드가 없습니다.");
        }

        // 부서 존재 여부 확인
        DeptVO checkDept = new DeptVO();
        checkDept.setDeptCd(deptCd);
        DeptVO foundDept = deptService.selectDeptDetail(checkDept);

        if (foundDept == null) {
            throw new BusinessException("삭제할 부서를 찾을 수 없습니다.");
        }

        DeptVO deleteDept = new DeptVO();
        deleteDept.setDeptCd(deptCd);
        int result = deptService.deleteDept(deleteDept);

        if (result <= 0) {
            throw new BusinessException("부서 삭제에 실패했습니다.");
        }

        log.info("부서 삭제 성공 - 부서코드: {}", deptCd);
        return ResponseEntity.ok(
            DefaultApiResponse.success("부서가 성공적으로 삭제되었습니다.")
        );
    }
}