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

const prisma = new PrismaClient();

/**
 * 获取用户偏好设置
 */
export async function getPreferences(userId: string) {
  const userIdNum = parseInt(userId);

  // 使用 upsert 语义，避免外键约束问题
  const preferences = await prisma.userPreference.upsert({
    where: { userId: userIdNum },
    update: {},
    create: {
      userId: userIdNum,
      playSpeed: 1.0,
      quality: 'standard',
      theme: 'light',
      defaultVoiceId: 'cherry',
      defaultVolume: 50,
      autoPlayNext: true,
      wifiOnlyDownload: false,
    },
  });

  return preferences;
}

/**
 * 更新用户偏好设置
 */
export async function updatePreferences(
  userId: string,
  data: {
    playSpeed?: number;
    quality?: string;
    theme?: string;
    defaultVoiceId?: string;
    defaultVolume?: number;
    autoPlayNext?: boolean;
    wifiOnlyDownload?: boolean;
  }
) {
  const userIdNum = parseInt(userId);

  // 使用 upsert 语义
  const existing = await prisma.userPreference.findUnique({
    where: { userId: userIdNum },
  });

  if (existing) {
    // 更新
    return await prisma.userPreference.update({
      where: { userId: userIdNum },
      data,
    });
  } else {
    // 创建
    return await prisma.userPreference.create({
      data: {
        userId: userIdNum,
        playSpeed: data.playSpeed ?? 1.0,
        quality: data.quality ?? 'standard',
        theme: data.theme ?? 'light',
        defaultVoiceId: data.defaultVoiceId ?? 'cherry',
        defaultVolume: data.defaultVolume ?? 50,
        autoPlayNext: data.autoPlayNext ?? true,
        wifiOnlyDownload: data.wifiOnlyDownload ?? false,
      },
    });
  }
}
