package top.tqx.demo_1.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.tqx.demo_1.common.Result;
import top.tqx.demo_1.dto.FAQCreateRequest;
import top.tqx.demo_1.dto.FAQListResponse;
import top.tqx.demo_1.dto.FAQUpdateRequest;
import top.tqx.demo_1.dto.FAQSuggestionListResponse;
import top.tqx.demo_1.entity.FAQ;
import top.tqx.demo_1.service.FAQService;

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

@Tag(name = "FAQ管理", description = "常见问题及建议管理接口")
@RestController
@RequestMapping("/faq")
@Slf4j
public class FAQController {

    @Autowired
    private FAQService faqService;

    @Operation(summary = "创建FAQ", description = "创建新的常见问题")
    @PostMapping
    public Result<FAQ> createFAQ(@RequestBody FAQCreateRequest request) {
        if (request.getQuestion() == null || request.getQuestion().isEmpty()) {
            return Result.error(400, "问题不能为空");
        }
        if (request.getAnswer() == null || request.getAnswer().isEmpty()) {
            return Result.error(400, "答案不能为空");
        }

        try {
            FAQ faq = faqService.createFAQ(request);
            log.info("创建FAQ成功: id={}", faq.getId());
            return Result.success("FAQ创建成功", faq);
        } catch (Exception e) {
            log.error("创建FAQ失败: {}", e.getMessage(), e);
            return Result.error(500, "创建FAQ失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取FAQ列表", description = "分页获取常见问题列表")
    @GetMapping
    public Result<FAQListResponse> getFAQList(
            @Parameter(description = "页码，默认1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小，默认20") @RequestParam(defaultValue = "20") Integer pageSize) {
        try {
            FAQListResponse response = faqService.getFAQList(page, pageSize);
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取FAQ列表失败", e);
            return Result.error(500, "获取FAQ列表失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取FAQ详情", description = "根据ID获取FAQ详细信息")
    @GetMapping("/{id}")
    public Result<FAQ> getFAQById(
            @Parameter(description = "FAQ ID") @PathVariable Long id) {
        try {
            FAQ faq = faqService.getFAQById(id);
            if (faq == null) {
                return Result.error(404, "FAQ不存在");
            }
            return Result.success(faq);
        } catch (Exception e) {
            log.error("获取FAQ详情失败: {}", e.getMessage(), e);
            return Result.error(500, "获取FAQ详情失败: " + e.getMessage());
        }
    }

    @Operation(summary = "更新FAQ", description = "更新FAQ信息，支持部分字段更新")
    @PutMapping("/{id}")
    public Result<FAQ> updateFAQ(
            @Parameter(description = "FAQ ID") @PathVariable Long id,
            @RequestBody FAQUpdateRequest request) {
        try {
            FAQ existing = faqService.getFAQById(id);
            if (existing == null) {
                return Result.error(404, "FAQ不存在");
            }

            FAQ updated = faqService.updateFAQ(id, request);
            log.info("更新FAQ成功: id={}", id);
            return Result.success("FAQ更新成功", updated);
        } catch (Exception e) {
            log.error("更新FAQ失败: {}", e.getMessage(), e);
            return Result.error(500, "更新FAQ失败: " + e.getMessage());
        }
    }

    @Operation(summary = "删除FAQ", description = "根据ID删除FAQ")
    @DeleteMapping("/{id}")
    public Result<Void> deleteFAQ(
            @Parameter(description = "FAQ ID") @PathVariable Long id) {
        try {
            FAQ existing = faqService.getFAQById(id);
            if (existing == null) {
                return Result.error(404, "FAQ不存在");
            }

            boolean success = faqService.deleteFAQ(id);
            if (success) {
                log.info("删除FAQ成功: id={}", id);
                return Result.success("FAQ删除成功");
            } else {
                return Result.error(500, "删除FAQ失败");
            }
        } catch (Exception e) {
            log.error("删除FAQ失败: {}", e.getMessage(), e);
            return Result.error(500, "删除FAQ失败: " + e.getMessage());
        }
    }

    @Operation(summary = "批量删除FAQ", description = "根据ID列表批量删除FAQ")
    @DeleteMapping("/batch")
    public Result<Integer> batchDeleteFAQs(
            @Parameter(description = "FAQ ID列表") @RequestParam String ids) {
        try {
            List<Long> idList = Arrays.stream(ids.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Long::parseLong)
                    .collect(Collectors.toList());

            if (idList.isEmpty()) {
                return Result.error(400, "ID列表不能为空");
            }

            int deletedCount = faqService.batchDeleteFAQs(idList);
            log.info("批量删除FAQ成功: count={}", deletedCount);
            return Result.success("批量删除成功", deletedCount);
        } catch (NumberFormatException e) {
            return Result.error(400, "ID格式不正确，请提供逗号分隔的数字ID");
        } catch (Exception e) {
            log.error("批量删除FAQ失败: {}", e.getMessage(), e);
            return Result.error(500, "批量删除失败: " + e.getMessage());
        }
    }

    @Operation(summary = "条件查询FAQ列表", description = "根据状态查询FAQ列表")
    @GetMapping("/list")
    public Result<List<FAQ>> listFAQs(
            @Parameter(description = "状态：pending/approved/rejected") @RequestParam(required = false) String status,
            @Parameter(description = "返回数量限制") @RequestParam(defaultValue = "100") Integer limit) {
        try {
            List<FAQ> faqs = faqService.listFAQs(status, limit);
            return Result.success(faqs);
        } catch (Exception e) {
            log.error("查询FAQ列表失败: {}", e.getMessage(), e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取FAQ建议列表", description = "分页获取用户反馈中产生的FAQ建议")
    @GetMapping("/suggestions")
    public Result<FAQSuggestionListResponse> getFAQSuggestions(
            @Parameter(description = "页码，默认1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小，默认20") @RequestParam(defaultValue = "20") Integer pageSize) {
        try {
            FAQSuggestionListResponse response = faqService.getFAQSuggestions(page, pageSize);
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取FAQ建议列表失败", e);
            return Result.error(500, "获取FAQ建议列表失败: " + e.getMessage());
        }
    }

    @Operation(summary = "批准FAQ建议", description = "将FAQ建议批准为正式FAQ，可修改答案")
    @PostMapping("/suggestions/{id}/approve")
    public Result<Void> approveSuggestion(
            @Parameter(description = "建议ID") @PathVariable Long id,
            @RequestBody(required = false) java.util.Map<String, String> requestBody) {
        try {
            String answer = requestBody != null ? requestBody.get("answer") : null;
            boolean success = faqService.approveSuggestion(id, answer);
            if (success) {
                return Result.success("批准成功");
            } else {
                return Result.error(500, "批准失败");
            }
        } catch (Exception e) {
            log.error("批准FAQ建议失败: {}", e.getMessage(), e);
            return Result.error(500, "批准FAQ建议失败: " + e.getMessage());
        }
    }

    @Operation(summary = "拒绝FAQ建议", description = "拒绝某个FAQ建议")
    @PostMapping("/suggestions/{id}/reject")
    public Result<Void> rejectSuggestion(
            @Parameter(description = "建议ID") @PathVariable Long id) {
        try {
            boolean success = faqService.rejectSuggestion(id);
            if (success) {
                return Result.success("拒绝成功");
            } else {
                return Result.error(500, "拒绝失败");
            }
        } catch (Exception e) {
            log.error("拒绝FAQ建议失败: {}", e.getMessage(), e);
            return Result.error(500, "拒绝FAQ建议失败: " + e.getMessage());
        }
    }
}