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

const prisma = new PrismaClient();

/**
 * 获取用户播放记录
 */
export async function getPlayProgress(userId: string, audioId?: number) {
  const userIdNum = parseInt(userId);
  const where: any = { userId: userIdNum };
  if (audioId) {
    where.audioId = audioId;
  }

  const records = await prisma.playRecord.findMany({
    where,
    include: {
      audio: {
        select: {
          id: true,
          title: true,
          audioUrl: true,
          audioDuration: true,
        },
      },
    },
    orderBy: { updatedAt: 'desc' },
  });

  return records;
}

/**
 * 保存播放进度
 */
export async function savePlayProgress(
  userId: string,
  audioId: number,
  progress: number,
  duration: number
) {
  const userIdNum = parseInt(userId);
  // 使用 upsert 语义：如果不存在则创建，存在则更新
  const existing = await prisma.playRecord.findUnique({
    where: {
      userId_audioId: {
        userId: userIdNum,
        audioId,
      },
    },
  });

  if (existing) {
    // 更新
    return await prisma.playRecord.update({
      where: {
        userId_audioId: {
          userId: userIdNum,
          audioId,
        },
      },
      data: {
        progress,
        duration,
      },
    });
  } else {
    // 创建
    return await prisma.playRecord.create({
      data: {
        userId: userIdNum,
        audioId,
        progress,
        duration,
      },
    });
  }
}

/**
 * 删除播放记录
 */
export async function deletePlayRecord(userId: string, audioId: number) {
  const userIdNum = parseInt(userId);
  return await prisma.playRecord.delete({
    where: {
      userId_audioId: {
        userId: userIdNum,
        audioId,
      },
    },
  });
}

/**
 * 更新播放进度
 */
export async function updatePlayProgress(
  userId: string,
  audioId: number,
  progress: number,
  duration?: number
) {
  const userIdNum = parseInt(userId);
  const data: any = { progress };
  if (duration !== undefined) {
    data.duration = duration;
  }

  return await prisma.playRecord.update({
    where: {
      userId_audioId: {
        userId: userIdNum,
        audioId,
      },
    },
    data,
  });
}

/**
 * 获取单个音频的播放进度
 */
export async function getSingleProgress(userId: string, audioId: number) {
  const userIdNum = parseInt(userId);
  const record = await prisma.playRecord.findUnique({
    where: {
      userId_audioId: {
        userId: userIdNum,
        audioId,
      },
    },
  });

  return record;
}
