package com.jeesharp.business.modules.mall.service.impl;

import com.jeesharp.business.modules.mall.entity.MallSearchLog;
import com.jeesharp.business.modules.mall.mapper.MallSearchLogMapper;
import com.jeesharp.business.modules.mall.service.MallSearchLogService;
import com.jeesharp.business.modules.mall.vo.MallSearchLogQueryVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 搜索历史 Service 实现类
 */
@Service
@Transactional(readOnly = true)
public class MallSearchLogServiceImpl extends CrudService<MallSearchLogMapper, MallSearchLog, MallSearchLogQueryVO> implements MallSearchLogService {

    private static final String IDS_SEPARATOR = ",";
    private static final long USER_SEARCH_HISTORY_LIMIT = 20L;

    @Override
    @Transactional(readOnly = false)
    public void createSearchLog(MallSearchLog entity) {
        entity.setSearchTime(new Date());
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateSearchLog(MallSearchLog entity) {
        entity.setSearchTime(new Date());
        update(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void recordSearchHistory(String memberId, String keyword) {
        if (memberId == null || keyword == null || keyword.trim().isEmpty()) {
            return;
        }
        MallSearchLog log = new MallSearchLog();
        log.setMemberId(memberId);
        log.setKeyword(keyword.trim());
        createSearchLog(log);
    }

    @Override
    public List<String> getUserSearchHistory(String memberId) {
        MallSearchLogQueryVO query = new MallSearchLogQueryVO();
        query.setMemberId(memberId);
        query.setPageSize(USER_SEARCH_HISTORY_LIMIT);
        return findList(query).stream()
                .map(MallSearchLog::getKeyword)
                .distinct()
                .collect(Collectors.toList());
    }

    @Override
    public List<Map<String, Object>> getHotSearchWords() {
        return List.of();
    }

    @Override
    @Transactional(readOnly = false)
    public void clearUserSearchHistory(String memberId) {
        // 保持原有空实现语义
    }
}
