import { prisma } from '../../models';
import { PaginationResult, VoiceParams } from '../../types';

// 获取用户音频列表
export async function getAudioList(
  userId: string,
  options: {
    page?: number;
    pageSize?: number;
    isFavorite?: boolean;
    keyword?: string;
    category?: string;
  }
): Promise<PaginationResult<any>> {
  const { page = 1, pageSize = 10, isFavorite, keyword, category } = options;

  // 构建查询条件
  const where: Record<string, any> = {};

  // 只有提供了有效的 userId 才添加用户过滤条件
  if (userId) {
    where.userId = parseInt(userId);
  }

  if (isFavorite !== undefined) {
    where.isFavorite = isFavorite;
  }

  if (keyword) {
    where.OR = [
      { title: { contains: keyword } },
      { text: { contains: keyword } },
    ];
  }

  if (category) {
    where.category = category;
  }

  const total = await prisma.audio.count({ where });
  const totalPages = Math.ceil(total / pageSize);

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

  return {
    list,
    total,
    page,
    pageSize,
    totalPages,
  };
}

// 获取单个音频
export async function getAudioById(audioId: string, userId: string): Promise<any | null> {
  const id = parseInt(audioId);
  if (isNaN(id)) {
    return null;
  }
  // 如果有有效的 userId，添加用户过滤
  if (userId) {
    return prisma.audio.findFirst({
      where: { id, userId: parseInt(userId) },
    });
  }
  // 没有 userId，返回该音频（允许匿名访问）
  return prisma.audio.findUnique({ where: { id } });
}

// 删除音频
export async function deleteAudio(audioId: string, userId: string): Promise<boolean> {
  // 验证 userId 是否为有效
  if (!userId) {
    return false;
  }
  const id = parseInt(audioId);
  if (isNaN(id)) {
    return false;
  }
  try {
    await prisma.audio.delete({
      where: { id, userId: parseInt(userId) },
    });
    return true;
  } catch {
    return false;
  }
}

// 切换收藏状态
export async function toggleFavorite(audioId: string, userId: string): Promise<any | null> {
  // 验证 userId 是否为有效
  if (!userId) {
    return null;
  }
  const id = parseInt(audioId);
  if (isNaN(id)) {
    return null;
  }
  const audio = await prisma.audio.findFirst({
    where: { id, userId: parseInt(userId) },
  });
  if (!audio) return null;

  const updated = await prisma.audio.update({
    where: { id: audio.id },
    data: { isFavorite: !audio.isFavorite },
  });
  return updated;
}

// 更新音频信息
export async function updateAudio(
  audioId: string,
  userId: string,
  data: { title?: string; tags?: string[] }
): Promise<any | null> {
  // 验证 userId 是否为有效
  if (!userId) {
    return null;
  }
  const id = parseInt(audioId);
  if (isNaN(id)) {
    return null;
  }
  const audio = await prisma.audio.findFirst({
    where: { id, userId: parseInt(userId) },
  });
  if (!audio) return null;

  const updated = await prisma.audio.update({
    where: { id: audio.id },
    data: {
      ...(data.title && { title: data.title }),
      ...(data.tags && { tags: JSON.stringify(data.tags) }),
    },
  });

  return updated;
}

// 获取用户使用统计
export async function getUserStats(userId: string): Promise<{
  totalAudios: number;
  totalDuration: number;
  totalWords: number;
  favoriteCount: number;
}> {
  // 验证 userId 是否为有效
  if (!userId) {
    return { totalAudios: 0, totalDuration: 0, totalWords: 0, favoriteCount: 0 };
  }

  const uid = parseInt(userId);
  if (isNaN(uid)) {
    return { totalAudios: 0, totalDuration: 0, totalWords: 0, favoriteCount: 0 };
  }

  const totalAudios = await prisma.audio.count({ where: { userId: uid } });
  
  const allAudios = await prisma.audio.findMany({
    where: { userId: uid },
    select: {
      audioDuration: true,
      wordCount: true,
      isFavorite: true,
    },
  });

  const totalDuration = allAudios.reduce((sum, a) => sum + a.audioDuration, 0);
  const totalWords = allAudios.reduce((sum, a) => sum + a.wordCount, 0);
  const favoriteCount = allAudios.filter(a => a.isFavorite).length;

  return {
    totalAudios,
    totalDuration,
    totalWords,
    favoriteCount,
  };
}