import { prisma } from '../../models';

/**
 * 搜索服务
 * 提供全局搜索功能（搜索书籍）
 */
export class SearchService {
  /**
   * 搜索书籍
   * @param query 搜索关键词
   * @param limit 返回结果数量限制
   */
  async searchAudio(query: string, limit = 20) {
    if (!query || query.trim() === '') {
      return [];
    }

    const searchQuery = query.trim();

    // 搜索书籍
    const results = await prisma.book.findMany({
      where: {
        OR: [
          { title: { contains: searchQuery } },
          { description: { contains: searchQuery } },
        ],
      },
      orderBy: {
        createdAt: 'desc',
      },
      take: limit,
    });

    return results;
  }

  /**
   * 获取热门搜索词
   * @param limit 返回数量限制
   */
  async getHotSearches(limit = 10) {
    const hotSearches = await prisma.hotSearch.findMany({
      orderBy: [
        { sort: 'desc' },
        { count: 'desc' },
      ],
      take: limit,
    });
    return hotSearches;
  }

  /**
   * 获取用户搜索历史
   * @param userId 用户ID
   * @param limit 返回数量限制
   */
  async getSearchHistory(userId: number, limit = 5) {
    const history = await prisma.searchHistory.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' },
      take: limit,
      distinct: ['keyword'], // 去重，相同关键词只保留最新一条
    });
    return history;
  }

  /**
   * 保存搜索历史
   * @param userId 用户ID
   * @param keyword 搜索关键词
   */
  async saveSearchHistory(userId: number, keyword: string) {
    if (!keyword || keyword.trim() === '') return;

    const trimmedKeyword = keyword.trim();

    // 删除同用户的相同关键词旧记录
    await prisma.searchHistory.deleteMany({
      where: { userId, keyword: trimmedKeyword },
    });

    // 创建新记录
    await prisma.searchHistory.create({
      data: {
        userId,
        keyword: trimmedKeyword,
      },
    });

    // 保持用户最多20条历史记录
    const allHistory = await prisma.searchHistory.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' },
    });

    if (allHistory.length > 20) {
      const toDelete = allHistory.slice(20);
      await prisma.searchHistory.deleteMany({
        where: { id: { in: toDelete.map((h) => h.id) } },
      });
    }

    // 更新热门搜索词计数
    const hotSearch = await prisma.hotSearch.findFirst({
      where: { keyword: trimmedKeyword },
    });

    if (hotSearch) {
      await prisma.hotSearch.update({
        where: { id: hotSearch.id },
        data: { count: { increment: 1 } },
      });
    } else {
      // 如果热门词不存在，创建新的（排序为0，count为1）
      await prisma.hotSearch.create({
        data: { keyword: trimmedKeyword, count: 1, sort: 0 },
      });
    }
  }

  /**
   * 删除用户搜索历史
   * @param userId 用户ID
   */
  async clearSearchHistory(userId: number) {
    await prisma.searchHistory.deleteMany({
      where: { userId },
    });
  }

  /**
   * 删除单条搜索历史
   * @param userId 用户ID
   * @param keyword 关键词
   */
  async deleteSearchHistoryItem(userId: number, keyword: string) {
    await prisma.searchHistory.deleteMany({
      where: { userId, keyword },
    });
  }
}

// 导出单例
export const searchService = new SearchService();
