import { prisma } from '../prisma.js'; /** * Get user's favorite apps, ordered by position. */ export async function getUserFavorites(userId: string) { return prisma.userFavorite.findMany({ where: { userId }, orderBy: { order: 'asc' }, include: { app: { include: { statuses: { orderBy: { checkedAt: 'desc' }, take: 1 } } } } }); } /** * Add an app to user's favorites (append to end). */ export async function addFavorite(userId: string, appId: string) { // Check if already favorited const existing = await prisma.userFavorite.findUnique({ where: { userId_appId: { userId, appId } } }); if (existing) { throw new Error('App is already in favorites'); } // Get the next order value const maxFav = await prisma.userFavorite.findFirst({ where: { userId }, orderBy: { order: 'desc' }, select: { order: true } }); const nextOrder = (maxFav?.order ?? -1) + 1; return prisma.userFavorite.create({ data: { userId, appId, order: nextOrder }, include: { app: true } }); } /** * Remove an app from user's favorites. */ export async function removeFavorite(userId: string, appId: string) { const existing = await prisma.userFavorite.findUnique({ where: { userId_appId: { userId, appId } } }); if (!existing) { throw new Error('App is not in favorites'); } await prisma.userFavorite.delete({ where: { userId_appId: { userId, appId } } }); } /** * Reorder user's favorites by setting order based on array position. */ export async function reorderFavorites(userId: string, favoriteIds: string[]) { const updates = favoriteIds.map((id, index) => prisma.userFavorite.update({ where: { id }, data: { order: index } }) ); return prisma.$transaction(updates); }