package com.jeesharp.business.modules.mall.controller;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.mall.application.MallSearchLogApplicationService;
import com.jeesharp.framework.memberauth.utils.MemberAuthUtils;
import com.jeesharp.framework.pojo.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

/**
 * 商城搜索历史移动端接口：会员 ID 由登录态解析。
 *
 * @author jeesharp
 * @since 2026-06-05
 */
@RestController
@RequestMapping(value = "${jeesharp.web.mobilePath}/mall/searchLog/v1")
@Tag(name = "搜索历史")
@AllArgsConstructor
public class MallSearchLogMobileController {

    private final MallSearchLogApplicationService mallSearchLogApplicationService;

    @Operation(summary = "记录搜索历史")
    @PostMapping(value = "record")
    public AjaxResult<Void> recordSearch(@RequestParam("keyword") String keyword) {
        String memberId = MemberAuthUtils.getLoginUserId();
        if (StrUtil.isBlank(memberId)) {
            return AjaxResult.fail(201, "请先登录");
        }
        if (StrUtil.isBlank(keyword)) {
            return AjaxResult.failMsg("关键词不能为空");
        }
        mallSearchLogApplicationService.recordSearchHistory(memberId, keyword.trim());
        return AjaxResult.ok();
    }

    @Operation(summary = "获取用户搜索历史")
    @GetMapping(value = "history")
    public AjaxResult<List<String>> getHistory() {
        String memberId = MemberAuthUtils.getLoginUserId();
        if (StrUtil.isBlank(memberId)) {
            return AjaxResult.okData(Collections.emptyList());
        }
        List<String> history = mallSearchLogApplicationService.getUserSearchHistory(memberId);
        return AjaxResult.okData(history);
    }

    @Operation(summary = "获取热门搜索词")
    @GetMapping(value = "hotWords")
    public AjaxResult<List<java.util.Map<String, Object>>> getHotWords() {
        List<java.util.Map<String, Object>> hotWords = mallSearchLogApplicationService.getHotSearchWords();
        return AjaxResult.okData(hotWords);
    }

    @Operation(summary = "清空用户搜索历史")
    @PostMapping(value = "clear")
    public AjaxResult<Void> clearHistory() {
        String memberId = MemberAuthUtils.getLoginUserId();
        if (StrUtil.isBlank(memberId)) {
            return AjaxResult.fail(201, "请先登录");
        }
        mallSearchLogApplicationService.clearUserSearchHistory(memberId);
        return AjaxResult.ok("清空成功");
    }
}
