| 1 | "use server"; |
| 2 | |
| 3 | import { auth } from "@/server/auth"; |
| 4 | import { db } from "@/server/db"; |
| 5 | |
| 6 | // Toggle like status for a theme |
| 7 | export async function toggleLikeTheme(themeId: string) { |
| 8 | try { |
| 9 | const session = await auth(); |
| 10 | if (!session?.user) { |
| 11 | return { |
| 12 | success: false, |
| 13 | message: "You must be signed in to like themes", |
| 14 | isLiked: false, |
| 15 | likeCount: 0, |
| 16 | }; |
| 17 | } |
| 18 | |
| 19 | // Check if theme exists |
| 20 | const theme = await db.presentationTheme.findUnique({ |
| 21 | where: { id: themeId }, |
| 22 | }); |
| 23 | |
| 24 | if (!theme) { |
| 25 | return { |
| 26 | success: false, |
| 27 | message: "Theme not found", |
| 28 | isLiked: false, |
| 29 | likeCount: 0, |
| 30 | }; |
| 31 | } |
| 32 | |
| 33 | // Check if already liked |
| 34 | const existingLike = await db.presentationThemeLike.findUnique({ |
| 35 | where: { |
| 36 | userId_themeId: { |
| 37 | userId: session.user.id, |
| 38 | themeId, |
| 39 | }, |
| 40 | }, |
| 41 | }); |
| 42 | |
| 43 | if (existingLike) { |
| 44 | // Remove like |
| 45 | await db.presentationThemeLike.delete({ |
| 46 | where: { |
| 47 | userId_themeId: { |
| 48 | userId: session.user.id, |
| 49 | themeId, |
| 50 | }, |
| 51 | }, |
| 52 | }); |
| 53 | } else { |
| 54 | // Add like |
| 55 | await db.presentationThemeLike.create({ |
| 56 | data: { |
| 57 | userId: session.user.id, |
| 58 | themeId, |
| 59 | }, |
| 60 | }); |
| 61 | } |
| 62 | |
| 63 | // Get updated like count |
| 64 | const likeCount = await db.presentationThemeLike.count({ |
| 65 | where: { themeId }, |
| 66 | }); |
| 67 | |
| 68 | // Check if user still likes it |
| 69 | const isLiked = !existingLike; |
| 70 | |
| 71 | return { |
| 72 | success: true, |
| 73 | isLiked, |
| 74 | likeCount, |
| 75 | message: isLiked ? "Theme liked" : "Theme unliked", |
| 76 | }; |
| 77 | } catch (error) { |
| 78 | console.error("Failed to toggle like:", error); |
| 79 | return { |
| 80 | success: false, |
| 81 | message: "Something went wrong. Please try again later.", |
| 82 | isLiked: false, |
| 83 | likeCount: 0, |
| 84 | }; |
| 85 | } |
| 86 | } |
| 87 |