package incheon.ags.pss.project.web;

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

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import incheon.ags.pss.project.service.ProjectService;
import incheon.ags.pss.project.vo.ProjectSearchVO;
import incheon.ags.pss.project.vo.ProjectVO;
import incheon.com.cmm.api.DefaultApiResponse;
import incheon.com.cmm.context.RequestContext;
import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/** * 안건지도 API 컨트롤러
 * @author hj
 */
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/pss/biz")
public class ProjectApiController {

    /** 안건지도 서비스 */
    private final ProjectService service;

    /**
     * 내 안건지도 목록 조회 API
     * @param pageIndex 페이지 인덱스
     * @param recordCountPerPage 페이지당 레코드 수
     * @param searchKeyword 검색 키워드
     * @return { list: List<ProjectVO>, paging: PaginationInfo }
     * @throws Exception 예외 발생 시
     */
    @GetMapping("/my-projects")
    @ResponseBody
    public ResponseEntity<DefaultApiResponse> getMyProjects(
            @RequestParam(defaultValue = "1") int pageIndex,
            @RequestParam(defaultValue = "3") int recordCountPerPage,
            @RequestParam(required = false) String searchKeyword) throws Exception {
    	
        String loginUserId = RequestContext.getCurrentUserId();
    	
        ProjectSearchVO projectSearchVO = new ProjectSearchVO();
        projectSearchVO.setPageIndex(pageIndex);
        projectSearchVO.setRecordCountPerPage(recordCountPerPage);
        
        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setCurrentPageNo(pageIndex);
        paginationInfo.setRecordCountPerPage(recordCountPerPage);
        paginationInfo.setPageSize(projectSearchVO.getPageSize());

        projectSearchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
        projectSearchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
        
        if (searchKeyword != null) {
            projectSearchVO.setSearchKeyword(searchKeyword);
        }
        projectSearchVO.setUserId(loginUserId);
        
        // 1. 목록 조회
        List<ProjectVO> list = service.selectProjectList(projectSearchVO);
        // 2. 카운트 조회
        int totalCount = service.selectProjectListCnt(projectSearchVO);
        paginationInfo.setTotalRecordCount(totalCount);
        
        // 3. Map에 담아 반환
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("paging", paginationInfo);
        
        return ResponseEntity.ok(DefaultApiResponse.success(result, "조회되었습니다."));
    }

    /**
     * 공유받은 안건지도 목록 조회 API
     * @param pageIndex 페이지 인덱스
     * @param recordCountPerPage 페이지당 레코드 수
     * @param searchKeyword 검색 키워드
     * @return { list: List<ProjectVO>, paging: PaginationInfo }
     * @throws Exception 예외 발생 시
     */
    @GetMapping("/shared-projects")
    @ResponseBody
    public ResponseEntity<DefaultApiResponse> getSharedProjects(
            @RequestParam(defaultValue = "1") int pageIndex,
            @RequestParam(defaultValue = "3") int recordCountPerPage,
            @RequestParam(required = false) String searchKeyword) throws Exception {
    	
        String loginUserId = RequestContext.getCurrentUserId();
    	
        ProjectSearchVO projectSearchVO = new ProjectSearchVO();
        projectSearchVO.setPageIndex(pageIndex);
        projectSearchVO.setRecordCountPerPage(recordCountPerPage);

        PaginationInfo paginationInfo = new PaginationInfo();
        paginationInfo.setCurrentPageNo(pageIndex);
        paginationInfo.setRecordCountPerPage(recordCountPerPage);
        paginationInfo.setPageSize(projectSearchVO.getPageSize());

        projectSearchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
        projectSearchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
        
        if (searchKeyword != null) {
            projectSearchVO.setSearchKeyword(searchKeyword);
        }
        projectSearchVO.setUserId(loginUserId);
        
        // 1. 목록 조회
        List<ProjectVO> list = service.selectSharedProjects(projectSearchVO);
        // 2. 카운트 조회
        int totalCount = service.selectSharedProjectsCnt(projectSearchVO);
        paginationInfo.setTotalRecordCount(totalCount);
        
        // 3. Map에 담아 반환
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("paging", paginationInfo);
        
        return ResponseEntity.ok(DefaultApiResponse.success(result, "조회되었습니다."));
    }

    /**
     * [추가] 안건지도 안건 연결 (bizNo <-> agndId)
     */
    @PostMapping("/link-agenda.do")
    public ResponseEntity<DefaultApiResponse> linkAgenda(@RequestBody ProjectVO vo) {
        try {
            if (vo.getBizNo() == null) {
                return ResponseEntity.ok(DefaultApiResponse.error(400, "Bad Request", "안건지도 번호가 누락되었습니다."));
            }

            // 서비스 호출 (updateProjectAgenda)
            // ProjectService에 casting 혹은 추가된 메서드 사용
            service.linkProjectAgenda(vo);

            String msg = "안건이 연결되었습니다.";
            if (vo.getAgndId() == null) {
                msg = "안건 연결이 해제되었습니다.";
            }
            return ResponseEntity.ok(DefaultApiResponse.success(null, msg));
        } catch (Exception e) {
//            log.error("안건 연결 실패", e);
        	log.error("안건 연결 실패: AgndId={}, ProjectId={}", vo.getAgndId(), vo.getBizNo(), e);
            return ResponseEntity.ok(DefaultApiResponse.error(500, "안건 연결 중 오류가 발생했습니다.", "안건 연결 실패"));
        }
    }
}