package incheon.ags.ias.tmap.web;

import incheon.ags.ias.tmap.service.TmapService;
import incheon.ags.ias.tmap.vo.TmapSearchVO;
import incheon.ags.ias.tmap.vo.TmapVO;
import incheon.ags.ias.tmap.web.dto.TmapRequestDTO;
import incheon.com.cmm.api.DefaultApiResponse;
import incheon.com.cmm.context.RequestContext;
import incheon.com.cmm.exception.BusinessException;
import incheon.com.cmm.exception.EntityNotFoundException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 주제도 관리 REST API Controller
 * Base URL: /api/v1/tmap
 */
@Tag(name = "주제도 관리 API", description = "주제도 등록, 수정, 삭제, 조회 API")
@Slf4j
@RestController
@RequestMapping("/api/v1/tmap")
@RequiredArgsConstructor
@Validated
public class TmapApiController {

    private final TmapService tmapService;

    /**
     * 주제도 목록 조회
     * GET /api/v1/tmap/list
     */
    @Operation(summary = "주제도 목록 조회", description = "전체 주제도 목록을 조회합니다")
    @GetMapping("/list")
    public ResponseEntity<List<Map<String, Object>>> getTmapList() throws Exception {
        TmapSearchVO searchVO = new TmapSearchVO();
        searchVO.setRecordCountPerPage(1000);
        searchVO.setFirstIndex(0);

        List<Map<String, Object>> result = tmapService.selectTmapList(searchVO);
        return ResponseEntity.ok(result);
    }

    /**
     * 주제도 상세 조회
     * GET /api/v1/tmap/{tmapSn}
     */
    @Operation(summary = "주제도 상세 조회", description = "특정 주제도의 상세 정보를 조회합니다")
    @GetMapping("/{tmapSn}")
    public ResponseEntity<TmapVO> getTmapDetail(
            @Parameter(description = "주제도일련번호", required = true, example = "1")
            @PathVariable Long tmapSn) throws Exception {

        TmapVO result = tmapService.selectTmapDetail(tmapSn);

        if (result == null) {
            throw new EntityNotFoundException("주제도");
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 주제도 등록
     * POST /api/v1/tmap
     */
    @Operation(summary = "주제도 등록", description = "새로운 주제도를 등록합니다")
    @PostMapping
    public ResponseEntity<DefaultApiResponse<Object>> createTmap(
            @Valid @RequestBody TmapRequestDTO requestDTO) throws Exception {

        log.info("주제도 등록 요청: {}", requestDTO.getTmapNm());

        String loginUserId = RequestContext.getCurrentUserId();

        TmapVO tmapVO = requestDTO.toEntity();
        tmapVO.setFrstRegId(loginUserId);
        tmapVO.setLastMdfcnId(loginUserId);

        int result = tmapService.insertTmap(tmapVO);

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

        log.info("주제도 등록 성공 - tmapNm: {}", tmapVO.getTmapNm());
        return ResponseEntity.ok(DefaultApiResponse.success(null, "주제도가 성공적으로 등록되었습니다."));
    }

    /**
     * 주제도 수정
     * PUT /api/v1/tmap/{tmapSn}
     */
    @Operation(summary = "주제도 수정", description = "기존 주제도 정보를 수정합니다")
    @PutMapping("/{tmapSn}")
    public ResponseEntity<DefaultApiResponse<Object>> updateTmap(
            @Parameter(description = "주제도일련번호", required = true, example = "1")
            @PathVariable Long tmapSn,
            @Valid @RequestBody TmapRequestDTO requestDTO) throws Exception {

        log.info("주제도 수정 요청 - tmapSn: {}, tmapNm: {}", tmapSn, requestDTO.getTmapNm());

        String loginUserId = RequestContext.getCurrentUserId();

        // 주제도 존재 여부 확인
        TmapVO existingTmap = tmapService.selectTmapDetail(tmapSn);
        if (existingTmap == null) {
            throw new EntityNotFoundException("주제도");
        }

        TmapVO tmapVO = requestDTO.toEntity();
        tmapVO.setTmapSn(tmapSn);
        tmapVO.setLastMdfcnId(loginUserId);

        int result = tmapService.updateTmap(tmapVO);

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

        log.info("주제도 수정 성공 - tmapSn: {}", tmapSn);
        return ResponseEntity.ok(DefaultApiResponse.success(null, "주제도가 성공적으로 수정되었습니다."));
    }

    /**
     * 주제도 삭제
     * DELETE /api/v1/tmap/{tmapSn}
     */
    @Operation(summary = "주제도 삭제", description = "주제도를 삭제합니다")
    @DeleteMapping("/{tmapSn}")
    public ResponseEntity<DefaultApiResponse<Object>> deleteTmap(
            @Parameter(description = "주제도일련번호", required = true, example = "1")
            @PathVariable Long tmapSn) throws Exception {

        log.info("주제도 삭제 요청 - tmapSn: {}", tmapSn);

        // 주제도 존재 여부 확인
        TmapVO existingTmap = tmapService.selectTmapDetail(tmapSn);
        if (existingTmap == null) {
            throw new EntityNotFoundException("주제도");
        }

        int result = tmapService.deleteTmap(tmapSn);

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

        log.info("주제도 삭제 성공 - tmapSn: {}", tmapSn);
        return ResponseEntity.ok(DefaultApiResponse.success(null, "주제도가 성공적으로 삭제되었습니다."));
    }
}
