import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

/**
 * 获取用户收藏列表
 */
export async function getFavorites(userId: string) {
  const userIdNum = parseInt(userId);
  
  const favorites = await prisma.favorite.findMany({
    where: { userId: userIdNum },
    include: {
      audio: {
        select: {
          id: true,
          title: true,
          text: true,
          audioUrl: true,
          audioDuration: true,
          wordCount: true,
          createdAt: true,
        },
      },
    },
    orderBy: { createdAt: 'desc' },
  });

  return favorites;
}

/**
 * 添加收藏
 */
export async function addFavorite(userId: string, audioId: number) {
  const userIdNum = parseInt(userId);
  
  // 检查是否已存在
  const existing = await prisma.favorite.findUnique({
    where: {
      userId_audioId: {
        userId: userIdNum,
        audioId,
      },
    },
  });

  if (existing) {
    return existing;
  }

  return await prisma.favorite.create({
    data: {
      userId: userIdNum,
      audioId,
    },
    include: {
      audio: {
        select: {
          id: true,
          title: true,
          text: true,
          audioUrl: true,
          audioDuration: true,
          wordCount: true,
          createdAt: true,
        },
      },
    },
  });
}

/**
 * 取消收藏
 */
export async function removeFavorite(userId: string, audioId: number) {
  const userIdNum = parseInt(userId);
  
  return await prisma.favorite.delete({
    where: {
      userId_audioId: {
        userId: userIdNum,
        audioId,
      },
    },
  });
}

/**
 * 检查是否已收藏
 */
export async function isFavorited(userId: string, audioId: number) {
  const userIdNum = parseInt(userId);
  
  const favorite = await prisma.favorite.findUnique({
    where: {
      userId_audioId: {
        userId: userIdNum,
        audioId,
      },
    },
  });

  return !!favorite;
}
