package incheon.ags.uis.dept.web;

import incheon.ags.uis.dept.service.DeptMappingService;
import incheon.ags.uis.dept.vo.DeptMappingVO;
import incheon.com.cmm.api.DefaultApiResponse;
import incheon.com.security.vo.LoginVO;
import org.egovframe.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
import org.egovframe.rte.psl.dataaccess.util.EgovMap;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/v1/dept")
public class DeptMappingApiController {

    private final DeptMappingService deptMappingService;

    public DeptMappingApiController(DeptMappingService deptMappingService) {
        this.deptMappingService = deptMappingService;
    }

    /**
     * 부서 조회 (매핑 여부 포함)
     *  - GET /api/v1/dept/list-for-mapping
     */
    @GetMapping("/list-for-mapping")
    public Map<String, Object> getDeptListForMapping(
            @RequestParam(value = "mngt", required = false) String mngt,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "searchType", required = false, defaultValue = "deptNm") String searchType,
            @RequestParam(value = "page", required = false, defaultValue = "1") int page,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize) {

        DeptMappingVO searchVO = new DeptMappingVO();
        searchVO.setMngt(mngt);
        searchVO.setKeyword(keyword);
        searchVO.setSearchType(searchType);
        searchVO.setPageIndex(page);
        searchVO.setRecordCountPerPage(pageSize);
        searchVO.setFirstIndex((page - 1) * pageSize);

        List<EgovMap> list = deptMappingService.selectDeptListForMapping(searchVO);
        int totalCount = deptMappingService.selectDeptListForMappingCount(searchVO);

        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("totalCount", totalCount);
        result.put("currentPage", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (int) Math.ceil((double) totalCount / pageSize));

        return result;
    }

    /**
     * 부서 매핑 삭제 (논리 삭제)
     *  - DELETE /api/v1/dept/mapping/{gid}
     */
    @DeleteMapping("/mapping/{gid}")
    public ResponseEntity<DefaultApiResponse<Void>> deleteDeptMapping(@PathVariable("gid") Long gid) {
        // 현재 로그인한 사용자 정보 가져오기
        LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
        String userId = loginVO.getUserId();

        DeptMappingVO vo = new DeptMappingVO();
        vo.setGid(gid);
        vo.setLastUpdusrId(userId);

        deptMappingService.deleteDeptMapping(vo);

        return ResponseEntity.ok(
            DefaultApiResponse.success(null, "부서 매핑 정보가 성공적으로 삭제되었습니다.")
        );
    }
}