package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.SearchDto;
import com.dora.service.SearchService;
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.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Max;

/**
 * 搜索控制器
 */
@Slf4j
@RestController
@RequestMapping("/user/search")
@RequiredArgsConstructor
@Validated
@Tag(name = "内容搜索", description = "工作流和课程的统一搜索接口")
public class SearchController {

    private final SearchService searchService;

    @GetMapping("")
    @Operation(summary = "搜索内容", description = "搜索工作流和课程，支持关键词、分类、类型等多种过滤条件，所有用户都可访问")
    public Result<SearchDto.SearchResponse> search(
            @Parameter(description = "搜索关键词", example = "AI图像处理") 
            @RequestParam String keyword,
            @Parameter(description = "内容类型", example = "all") 
            @RequestParam(defaultValue = "all") String type,
            @Parameter(description = "分类过滤", example = "人工智能") 
            @RequestParam(required = false) String category,
            @Parameter(description = "是否仅显示免费内容", example = "false") 
            @RequestParam(defaultValue = "false") Boolean freeOnly,
            @Parameter(description = "排序方式", example = "relevance") 
            @RequestParam(defaultValue = "relevance") String sortBy,
            @Parameter(description = "排序方向", example = "desc") 
            @RequestParam(defaultValue = "desc") String sortOrder,
            @Parameter(description = "页码", example = "1") 
            @RequestParam(defaultValue = "1") @Min(1) Integer page,
            @Parameter(description = "每页数量", example = "20") 
            @RequestParam(defaultValue = "20") @Min(1) @Max(100) Integer size) {
        
        try {
            // 参数验证
            if (!StringUtils.hasText(keyword) || keyword.trim().length() < 2) {
                return Result.error(400, "搜索关键词至少需要2个字符");
            }
            
            if (!isValidType(type)) {
                return Result.error(400, "无效的内容类型，支持：all, course, workflow");
            }
            
            if (!isValidSortBy(sortBy)) {
                return Result.error(400, "无效的排序方式，支持：relevance, createTime, updateTime, viewCount, likeCount");
            }
            
            if (!isValidSortOrder(sortOrder)) {
                return Result.error(400, "无效的排序方向，支持：asc, desc");
            }
            
            // 构建搜索请求
            SearchDto.SearchRequest request = new SearchDto.SearchRequest();
            request.setKeyword(keyword.trim());
            request.setType(type);
            request.setCategory(category);
            request.setFreeOnly(freeOnly);
            request.setSortBy(sortBy);
            request.setSortOrder(sortOrder);
            request.setPage(page);
            request.setSize(size);
            
            log.info("搜索内容 - keyword: {}, type: {}, category: {}, freeOnly: {}, sortBy: {}, page: {}, size: {}", 
                    keyword, type, category, freeOnly, sortBy, page, size);
            
            SearchDto.SearchResponse response = searchService.search(request);
            return Result.success(response);
            
        } catch (Exception e) {
            log.error("搜索内容失败 - keyword: {}, type: {}", keyword, type, e);
            if (e instanceof com.dora.exception.BusinessException) {
                return Result.error(400, e.getMessage());
            }
            return Result.error(500, "搜索失败，请重试");
        }
    }

    @PostMapping("")
    @Operation(summary = "高级搜索", description = "通过POST方式进行高级搜索，支持更复杂的搜索条件")
    public Result<SearchDto.SearchResponse> advancedSearch(@Valid @RequestBody SearchDto.SearchRequest request) {
        try {
            // 参数验证
            if (!StringUtils.hasText(request.getKeyword()) || request.getKeyword().trim().length() < 2) {
                return Result.error(400, "搜索关键词至少需要2个字符");
            }
            
            if (!isValidType(request.getType())) {
                return Result.error(400, "无效的内容类型，支持：all, course, workflow");
            }
            
            if (!isValidSortBy(request.getSortBy())) {
                return Result.error(400, "无效的排序方式，支持：relevance, createTime, updateTime, viewCount, likeCount");
            }
            
            if (!isValidSortOrder(request.getSortOrder())) {
                return Result.error(400, "无效的排序方向，支持：asc, desc");
            }
            
            // 清理关键词
            request.setKeyword(request.getKeyword().trim());
            
            log.info("高级搜索 - keyword: {}, type: {}, category: {}, freeOnly: {}, sortBy: {}, page: {}, size: {}", 
                    request.getKeyword(), request.getType(), request.getCategory(), 
                    request.getFreeOnly(), request.getSortBy(), request.getPage(), request.getSize());
            
            SearchDto.SearchResponse response = searchService.search(request);
            return Result.success(response);
            
        } catch (Exception e) {
            log.error("高级搜索失败 - keyword: {}, type: {}", request.getKeyword(), request.getType(), e);
            if (e instanceof com.dora.exception.BusinessException) {
                return Result.error(400, e.getMessage());
            }
            return Result.error(500, "搜索失败，请重试");
        }
    }

    @GetMapping("/stats")
    @Operation(summary = "搜索统计", description = "获取搜索结果的统计信息，包括各类型数量和分类分布")
    public Result<SearchDto.SearchStats> getSearchStats(
            @Parameter(description = "搜索关键词", example = "AI图像处理") 
            @RequestParam String keyword,
            @Parameter(description = "内容类型", example = "all") 
            @RequestParam(defaultValue = "all") String type,
            @Parameter(description = "分类过滤", example = "人工智能") 
            @RequestParam(required = false) String category,
            @Parameter(description = "是否仅显示免费内容", example = "false") 
            @RequestParam(defaultValue = "false") Boolean freeOnly) {
        
        try {
            // 参数验证
            if (!StringUtils.hasText(keyword) || keyword.trim().length() < 2) {
                return Result.error(400, "搜索关键词至少需要2个字符");
            }
            
            if (!isValidType(type)) {
                return Result.error(400, "无效的内容类型，支持：all, course, workflow");
            }
            
            // 构建搜索请求
            SearchDto.SearchRequest request = new SearchDto.SearchRequest();
            request.setKeyword(keyword.trim());
            request.setType(type);
            request.setCategory(category);
            request.setFreeOnly(freeOnly);
            
            log.info("获取搜索统计 - keyword: {}, type: {}, category: {}, freeOnly: {}", 
                    keyword, type, category, freeOnly);
            
            SearchDto.SearchStats stats = searchService.getSearchStats(request);
            return Result.success(stats);
            
        } catch (Exception e) {
            log.error("获取搜索统计失败 - keyword: {}, type: {}", keyword, type, e);
            return Result.error(500, "获取搜索统计失败，请重试");
        }
    }

    /**
     * 验证内容类型是否有效
     */
    private boolean isValidType(String type) {
        return "all".equals(type) || "course".equals(type) || "workflow".equals(type);
    }

    /**
     * 验证排序方式是否有效
     */
    private boolean isValidSortBy(String sortBy) {
        return "relevance".equals(sortBy) || "createTime".equals(sortBy) || 
               "updateTime".equals(sortBy) || "viewCount".equals(sortBy) || "likeCount".equals(sortBy);
    }

    /**
     * 验证排序方向是否有效
     */
    private boolean isValidSortOrder(String sortOrder) {
        return "asc".equals(sortOrder) || "desc".equals(sortOrder);
    }
}
