package com.unicorn.hgzero.meeting.infra.controller;

import com.unicorn.hgzero.common.dto.ApiResponse;
import com.unicorn.hgzero.meeting.biz.dto.TemplateDTO;
import com.unicorn.hgzero.meeting.biz.service.TemplateService;
import com.unicorn.hgzero.meeting.infra.dto.response.TemplateListResponse;
import com.unicorn.hgzero.meeting.infra.dto.response.TemplateDetailResponse;
import com.unicorn.hgzero.meeting.infra.cache.CacheService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 템플릿 관리 API Controller
 * 템플릿 목록 조회, 상세 조회 기능
 */
@RestController
@RequestMapping("/api/templates")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "Template", description = "템플릿 관리 API")
public class TemplateController {

    private final TemplateService templateService;
    private final CacheService cacheService;

    /**
     * 템플릿 목록 조회
     * GET /api/templates
     */
    @GetMapping
    @Operation(summary = "템플릿 목록 조회", description = "사용 가능한 템플릿 목록을 조회합니다")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "조회 성공"),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "잘못된 요청"),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "인증 실패")
    })
    public ResponseEntity<ApiResponse<TemplateListResponse>> getTemplateList(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-User-Name") String userName,
            @Parameter(description = "템플릿 카테고리") @RequestParam(required = false) String category,
            @Parameter(description = "활성 상태 (true: 활성, false: 비활성)") @RequestParam(required = false) Boolean isActive) {

        log.info("템플릿 목록 조회 요청 - userId: {}, category: {}, isActive: {}", 
                userId, category, isActive);

        try {
            // 캐시 확인
            String cacheKey = String.format("templates:list:%s:%s", 
                    (category != null ? category : "all"), 
                    (isActive != null ? isActive.toString() : "all"));
            TemplateListResponse cachedResponse = cacheService.getCachedTemplateList(cacheKey);
            if (cachedResponse != null) {
                log.debug("캐시된 템플릿 목록 반환");
                return ResponseEntity.ok(ApiResponse.success(cachedResponse));
            }

            // 템플릿 목록 조회
            List<TemplateDTO> templates = templateService.getTemplateList(category, isActive);
            
            // 응답 DTO 생성
            List<TemplateListResponse.TemplateItem> templateItems = templates.stream()
                    .map(this::convertToTemplateItem)
                    .collect(Collectors.toList());

            TemplateListResponse response = TemplateListResponse.builder()
                    .templateList(templateItems)
                    .totalCount(templateItems.size())
                    .build();

            // 캐시 저장
            cacheService.cacheTemplateList(cacheKey, response);

            log.info("템플릿 목록 조회 성공 - count: {}", templateItems.size());
            return ResponseEntity.ok(ApiResponse.success(response));

        } catch (Exception e) {
            log.error("템플릿 목록 조회 실패", e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.errorWithType("템플릿 목록 조회에 실패했습니다"));
        }
    }

    /**
     * 템플릿 상세 조회
     * GET /api/templates/{templateId}
     */
    @GetMapping("/{templateId}")
    @Operation(summary = "템플릿 상세 조회", description = "템플릿 상세 정보를 조회합니다")
    public ResponseEntity<ApiResponse<TemplateDetailResponse>> getTemplateDetail(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-User-Name") String userName,
            @Parameter(description = "템플릿 ID") @PathVariable String templateId) {

        log.info("템플릿 상세 조회 요청 - userId: {}, templateId: {}", userId, templateId);

        try {
            // 캐시 확인
            TemplateDetailResponse cachedResponse = cacheService.getCachedTemplateDetail(templateId);
            if (cachedResponse != null) {
                log.debug("캐시된 템플릿 상세 반환 - templateId: {}", templateId);
                return ResponseEntity.ok(ApiResponse.success(cachedResponse));
            }

            // 템플릿 조회
            TemplateDTO templateDTO = templateService.getTemplateById(templateId);
            
            // 응답 DTO 생성
            TemplateDetailResponse response = convertToTemplateDetailResponse(templateDTO);

            // 캐시 저장
            cacheService.cacheTemplateDetail(templateId, response);

            log.info("템플릿 상세 조회 성공 - templateId: {}", templateId);
            return ResponseEntity.ok(ApiResponse.success(response));

        } catch (Exception e) {
            log.error("템플릿 상세 조회 실패 - templateId: {}", templateId, e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.errorWithType("템플릿 상세 조회에 실패했습니다"));
        }
    }

    // Helper methods
    private TemplateListResponse.TemplateItem convertToTemplateItem(TemplateDTO templateDTO) {
        // 섹션 정보 변환
        List<TemplateListResponse.TemplateSectionInfo> sections = templateDTO.getSections().stream()
                .map(section -> TemplateListResponse.TemplateSectionInfo.builder()
                        .title(section.getTitle())
                        .description(section.getDescription())
                        .orderIndex(section.getOrderIndex())
                        .isRequired(section.isRequired())
                        .build())
                .collect(Collectors.toList());

        return TemplateListResponse.TemplateItem.builder()
                .templateId(templateDTO.getTemplateId())
                .name(templateDTO.getName())
                .description(templateDTO.getDescription())
                .category(templateDTO.getCategory())
                .isActive(templateDTO.isActive())
                .usageCount(templateDTO.getUsageCount())
                .createdAt(templateDTO.getCreatedAt())
                .lastUsedAt(templateDTO.getLastUsedAt())
                .createdBy(templateDTO.getCreatedBy())
                .sections(sections)
                .build();
    }

    private TemplateDetailResponse convertToTemplateDetailResponse(TemplateDTO templateDTO) {
        // 섹션 상세 정보 변환
        List<TemplateDetailResponse.SectionDetail> sections = templateDTO.getSections().stream()
                .map(section -> TemplateDetailResponse.SectionDetail.builder()
                        .sectionId(section.getSectionId())
                        .title(section.getTitle())
                        .description(section.getDescription())
                        .content(section.getContent())
                        .orderIndex(section.getOrderIndex())
                        .isRequired(section.isRequired())
                        .inputType(section.getInputType())
                        .placeholder(section.getPlaceholder())
                        .maxLength(section.getMaxLength())
                        .isEditable(section.isEditable())
                        .build())
                .collect(Collectors.toList());

        return TemplateDetailResponse.builder()
                .templateId(templateDTO.getTemplateId())
                .name(templateDTO.getName())
                .description(templateDTO.getDescription())
                .category(templateDTO.getCategory())
                .isActive(templateDTO.isActive())
                .usageCount(templateDTO.getUsageCount())
                .createdAt(templateDTO.getCreatedAt())
                .lastUsedAt(templateDTO.getLastUsedAt())
                .createdBy(templateDTO.getCreatedBy())
                .sections(sections)
                .build();
    }
}