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

/**
 * 分类服务
 */
export class CategoriesService {
  /**
   * 获取所有分类
   */
  async getCategories() {
    // 返回默认分类
    return [
      { id: 1, name: '全部', icon: '🎵' },
      { id: 2, name: '故事', icon: '📖' },
      { id: 3, name: '小说', icon: '📚' },
      { id: 4, name: '儿童', icon: '👶' },
      { id: 5, name: '知识', icon: '💡' },
      { id: 6, name: '娱乐', icon: '🎮' },
    ];
  }

  /**
   * 按分类获取音频
   */
  async getAudiosByCategory(categoryId: number, page = 1, pageSize = 20) {
    // categoryId 1 表示全部
    if (categoryId === 1) {
      return this.getAllAudios(page, pageSize);
    }

    const where = categoryId > 1 ? {
      // 使用 tags 字段匹配分类
      tags: {
        contains: this.getCategoryTag(categoryId)
      }
    } : {};

    const [list, total] = await Promise.all([
      prisma.audio.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
      }),
      prisma.audio.count({ where }),
    ]);

    return {
      list,
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    };
  }

  /**
   * 获取全部音频
   */
  private async getAllAudios(page: number, pageSize: number) {
    const [list, total] = await Promise.all([
      prisma.audio.findMany({
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
      }),
      prisma.audio.count(),
    ]);

    return {
      list,
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    };
  }

  /**
   * 获取分类对应的标签
   */
  private getCategoryTag(categoryId: number): string {
    const tags: Record<number, string> = {
      2: '故事',
      3: '小说',
      4: '儿童',
      5: '知识',
      6: '娱乐',
    };
    return tags[categoryId] || '';
  }
}

export const categoriesService = new CategoriesService();
