All files / src/lib/services UserService.ts

0% Statements 0/192
0% Branches 0/120
0% Functions 0/17
0% Lines 0/189

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import crypto from 'node:crypto';
import { UserRole } from '@prisma/client';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { ZodError } from 'zod';
import {
  generateResetToken,
  sendPasswordResetEmail,
  sendWelcomeEmail,
} from '@/lib/email/nodemailer';
import {
  USER_FAVORITE_MESSAGE_KEYS,
  USER_FOLLOW_MESSAGE_KEYS,
  USER_REGISTER_MESSAGE_KEYS,
} from '@/lib/graphql/MESSAGE_KEYS';
import type {
  ChangePasswordInput,
  SetNewPasswordInput,
  UpdateUserInput,
} from '@/lib/graphql/resolvers/user/mutations/types';
import { prisma } from '@/lib/prisma/prisma';
import { redis } from '@/lib/redis/redis';
import { ErrorTypes } from '@/lib/validation/errorCatalog';
import { throwCustomError } from '@/lib/validation/throwCustomError';
import type { ZodIssueMinimal } from '@/lib/validation/types';
import {
  customValidationSchema,
  loginValidationSchema,
  nameValidationSchema,
  passwordEditValidationSchema,
  resetPasswordValidationSchema,
  setNewPasswordValidationSchema,
} from '@/lib/validation/validation';
import type { CreateUserArgs, LoginUserArgs } from '@/types/user';
 
const JWT_SECRET =
  process.env.JWT_SECRET || 'your-secret-key-change-this-in-production';
const JWT_EXPIRES_IN = '7d';
const SALT_ROUNDS = 10;
const LATEST_RECIPES_LIMIT = 4;
 
export const UserService = {
  // Queries
  async getUserById(id: string) {
    const user = await prisma.user.findUnique({
      where: { id },
      include: {
        recipes: {
          include: { ingredients: true, preparationSteps: true },
        },
        favoriteRecipes: {
          include: { ingredients: true, preparationSteps: true },
        },
      },
    });
    if (!user) {
      return throwCustomError('User not found', ErrorTypes.NOT_FOUND);
    }
    return user;
  },
 
  async getFavoriteRecipes(userId: string, limit?: number) {
    const cacheKey = `user:${userId}:favorites:${limit || 'all'}`;
 
    if (redis) {
      try {
        const cached = await redis.get(cacheKey);
        if (cached) return cached;
      } catch (error) {
        console.error('Redis cache get error:', error);
      }
    }
 
    const user = await prisma.user.findUnique({
      where: { id: userId },
      include: {
        favoriteRecipes: {
          include: { ingredients: true, preparationSteps: true },
          orderBy: { createdAt: 'desc' },
          ...(limit ? { take: limit } : {}),
        },
      },
    });
    if (!user) {
      return throwCustomError('User not found', ErrorTypes.NOT_FOUND);
    }
 
    if (redis) {
      try {
        await redis.setex(cacheKey, 60, user.favoriteRecipes);
      } catch (error) {
        console.error('Redis cache set error:', error);
      }
    }
 
    return user.favoriteRecipes;
  },
 
  async getFollowing(userId: string, limit?: number) {
    const cacheKey = `user:${userId}:following:${limit || 'all'}`;
 
    if (redis) {
      try {
        const cached = await redis.get(cacheKey);
        if (cached) return cached;
      } catch (error) {
        console.error('Redis cache get error:', error);
      }
    }
 
    const [follows, totalFollowing] = await Promise.all([
      prisma.follow.findMany({
        where: { followerId: userId },
        include: {
          following: {
            include: {
              recipes: {
                orderBy: { createdAt: 'desc' },
                take: LATEST_RECIPES_LIMIT,
                include: { ingredients: true, preparationSteps: true },
              },
              _count: { select: { recipes: true } },
            },
          },
        },
        orderBy: { createdAt: 'desc' },
        ...(limit ? { take: limit } : {}),
      }),
      prisma.follow.count({ where: { followerId: userId } }),
    ]);
 
    const users = follows.map((follow) => ({
      id: follow.following.id,
      firstName: follow.following.firstName,
      lastName: follow.following.lastName,
      userName: follow.following.userName,
      recipeCount: follow.following._count.recipes,
      followedAt: follow.createdAt,
      latestRecipes: follow.following.recipes,
    }));
 
    const result = { users, totalFollowing };
 
    if (redis) {
      try {
        await redis.setex(cacheKey, 60, result);
      } catch (error) {
        console.error('Redis cache set error:', error);
      }
    }
 
    return result;
  },
 
  // Mutations
  async createUser(userRegisterInput: CreateUserArgs['userRegisterInput']) {
    const {
      firstName,
      lastName,
      userName,
      email,
      password,
      confirmPassword,
      locale,
    } = userRegisterInput;
 
    try {
      customValidationSchema.parse({
        firstName,
        lastName,
        userName,
        email,
        password,
        confirmPassword,
      });
    } catch (error) {
      if (error instanceof ZodError) {
        const firstErrorMessage =
          error.issues[0]?.message || 'Validation failed';
        return throwCustomError(
          firstErrorMessage,
          ErrorTypes.VALIDATION_ERROR,
          {
            messageKey: USER_REGISTER_MESSAGE_KEYS.VALIDATION_ERROR,
            zodIssues: error.issues as ZodIssueMinimal[],
            originalError: error,
          },
        );
      }
 
      return throwCustomError('Invalid input data', ErrorTypes.BAD_REQUEST);
    }
 
    const existingUser = await prisma.user.findFirst({
      where: {
        OR: [
          { userName: { equals: userName, mode: 'insensitive' } },
          { email: { equals: email, mode: 'insensitive' } },
        ],
      },
    });
 
    if (existingUser) {
      if (existingUser.userName.toLowerCase() === userName.toLowerCase()) {
        return throwCustomError(
          'This username is already taken',
          ErrorTypes.CONFLICT,
          {
            messageKey: USER_REGISTER_MESSAGE_KEYS.USERNAME_TAKEN,
          },
        );
      }
 
      if (existingUser.email.toLowerCase() === email.toLowerCase()) {
        return throwCustomError(
          'This email address is already registered',
          ErrorTypes.CONFLICT,
          {
            messageKey: USER_REGISTER_MESSAGE_KEYS.EMAIL_TAKEN,
          },
        );
      }
    }
 
    const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS);
 
    const newUser = await prisma.user.create({
      data: {
        firstName,
        lastName,
        userName,
        email: email.toLowerCase(),
        password: hashedPassword,
        locale: locale || 'en-gb',
        role: UserRole.USER,
      },
    });
 
    sendWelcomeEmail(newUser.email, newUser.firstName).catch((error) => {
      console.error('Error sending welcome email:', error);
    });
 
    return {
      success: true,
      message: 'User successfully created',
      messageKey: USER_REGISTER_MESSAGE_KEYS.SUCCESS,
      statusCode: 201,
      user: {
        ...newUser,
        recipes: [],
        favoriteRecipes: [],
      },
    };
  },
 
  async loginUser(userLoginInput: LoginUserArgs['userLoginInput']) {
    const { email, password } = userLoginInput;
 
    const validation = loginValidationSchema.safeParse(userLoginInput);
    if (!validation.success) {
      return throwCustomError(
        'Invalid input data',
        ErrorTypes.VALIDATION_ERROR,
        {
          zodIssues: validation.error.issues as ZodIssueMinimal[],
        },
      );
    }
 
    const user = await prisma.user.findUnique({
      where: { email: email.toLowerCase() },
    });
 
    if (!user) {
      return throwCustomError(
        'Invalid email address or password',
        ErrorTypes.UNAUTHORIZED,
      );
    }
 
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      return throwCustomError(
        'Invalid email address or password',
        ErrorTypes.UNAUTHORIZED,
      );
    }
 
    const token = jwt.sign(
      {
        userId: user.id,
        userName: user.userName,
        email: user.email,
        role: user.role,
      },
      JWT_SECRET,
      { expiresIn: JWT_EXPIRES_IN },
    );
 
    return {
      token,
      userId: user.id,
      user: {
        ...user,
        recipes: [],
        favoriteRecipes: [],
      },
    };
  },
 
  async changePassword(
    userId: string,
    passwordEditInput: ChangePasswordInput['passwordEditInput'],
  ) {
    const validation =
      passwordEditValidationSchema.safeParse(passwordEditInput);
    if (!validation.success) {
      return throwCustomError(
        'Invalid input data',
        ErrorTypes.VALIDATION_ERROR,
        {
          zodIssues: validation.error.issues,
        },
      );
    }
 
    const { currentPassword, newPassword } = passwordEditInput;
 
    const user = await prisma.user.findUnique({ where: { id: userId } });
    if (!user) {
      return throwCustomError('User not found', ErrorTypes.NOT_FOUND);
    }
 
    const isMatch = await bcrypt.compare(currentPassword, user.password);
    if (!isMatch) {
      return throwCustomError(
        'Invalid current password',
        ErrorTypes.BAD_REQUEST,
      );
    }
 
    const hashedPassword = await bcrypt.hash(newPassword, SALT_ROUNDS);
 
    await prisma.user.update({
      where: { id: userId },
      data: { password: hashedPassword },
    });
 
    return true;
  },
 
  async resetPassword(email: string) {
    const validation = resetPasswordValidationSchema.safeParse({ email });
    if (!validation.success) {
      return throwCustomError(
        'Invalid email address',
        ErrorTypes.VALIDATION_ERROR,
        {
          zodIssues: validation.error.issues,
        },
      );
    }
 
    const normalizedEmail = email.toLowerCase();
    const user = await prisma.user.findUnique({
      where: { email: normalizedEmail },
    });
 
    if (!user) {
      console.log(
        `Password reset requested for non-existent email: ${normalizedEmail}`,
      );
      return {
        success: true,
        message:
          'If an account with that email exists, a password reset link has been sent.',
      };
    }
 
    const resetToken = generateResetToken();
    const hashedToken = crypto
      .createHash('sha256')
      .update(resetToken)
      .digest('hex');
    const resetExpires = new Date(Date.now() + 60 * 60 * 1000);
 
    await prisma.user.update({
      where: { email: normalizedEmail },
      data: {
        resetPasswordToken: hashedToken,
        resetPasswordExpires: resetExpires,
      },
    });
 
    try {
      await sendPasswordResetEmail(user.email, resetToken);
    } catch (error) {
      console.error('Error sending reset email:', error);
      return throwCustomError(
        'Failed to send password reset email',
        ErrorTypes.INTERNAL_SERVER_ERROR,
      );
    }
 
    return {
      success: true,
      message:
        'If an account with that email exists, a password reset link has been sent.',
    };
  },
 
  async setNewPassword(input: SetNewPasswordInput) {
    const { token, newPassword } = input;
    const validation = setNewPasswordValidationSchema.safeParse({
      newPassword,
      confirmPassword: newPassword,
    });
 
    if (!validation.success) {
      return throwCustomError(
        'Password must be at least 8 characters long and include uppercase, lowercase letters and a number',
        ErrorTypes.VALIDATION_ERROR,
        { zodIssues: validation.error.issues },
      );
    }
 
    const hashedToken = crypto.createHash('sha256').update(token).digest('hex');
    const user = await prisma.user.findFirst({
      where: {
        resetPasswordToken: hashedToken,
        resetPasswordExpires: { gt: new Date() },
      },
    });
 
    if (!user) {
      return throwCustomError(
        'Invalid or expired reset token. Please request a new password reset.',
        ErrorTypes.BAD_REQUEST,
      );
    }
 
    const hashedPassword = await bcrypt.hash(newPassword, SALT_ROUNDS);
 
    await prisma.user.update({
      where: { id: user.id },
      data: {
        password: hashedPassword,
        resetPasswordToken: null,
        resetPasswordExpires: null,
      },
    });
 
    console.log(`Password successfully reset for user: ${user.email}`);
 
    return {
      success: true,
      message:
        'Password successfully reset. You can now login with your new password.',
    };
  },
 
  async updateUser(
    userId: string,
    userUpdateInput: UpdateUserInput['userUpdateInput'],
  ) {
    const { firstName, lastName, locale } = userUpdateInput;
    if (firstName || lastName) {
      nameValidationSchema.parse({
        firstName: firstName || 'placeholder',
        lastName: lastName || 'placeholder',
      });
    }
 
    const user = await prisma.user.findUnique({ where: { id: userId } });
    if (!user) {
      return throwCustomError('User not found', ErrorTypes.NOT_FOUND);
    }
 
    const updatedUser = await prisma.user.update({
      where: { id: userId },
      data: {
        firstName: firstName ?? user.firstName,
        lastName: lastName ?? user.lastName,
        locale: locale ?? user.locale,
      },
    });
 
    return {
      success: true,
      message: 'User updated successfully',
      user: updatedUser,
    };
  },
 
  async deleteUser(currentUserId: string, currentUserRole: string, id: string) {
    if (currentUserRole !== 'ADMIN' && currentUserId !== id) {
      return throwCustomError(
        'Unauthorized operation - insufficient permissions',
        ErrorTypes.FORBIDDEN,
      );
    }
 
    const user = await prisma.user.findUnique({ where: { id } });
    if (!user) {
      return throwCustomError('User not found', ErrorTypes.NOT_FOUND);
    }
 
    await prisma.user.delete({ where: { id } });
 
    if (redis) {
      try {
        await Promise.all([
          redis.del(`user:${id}:favorites:all`),
          redis.del(`user:${id}:following:all`),
          redis.del(`recipes:user:${id}:all`),
        ]);
      } catch (error) {
        console.error('Redis cache invalidation error:', error);
      }
    }
 
    return true;
  },
 
  async deleteAllUser(currentUserId: string, currentUserRole: string) {
    if (currentUserRole !== 'ADMIN') {
      return throwCustomError(
        'Unauthorized operation - admin rights required',
        ErrorTypes.FORBIDDEN,
      );
    }
 
    const result = await prisma.user.deleteMany({
      where: { id: { not: currentUserId } },
    });
    return result.count;
  },
 
  async addToFavoriteRecipes(
    currentUserId: string,
    currentUserRole: string,
    targetUserId: string,
    recipeId: string,
  ) {
    if (currentUserId !== targetUserId && currentUserRole !== 'ADMIN') {
      return {
        success: false,
        message: 'Unauthorized operation - insufficient permissions',
        messageKey: USER_FAVORITE_MESSAGE_KEYS.UNAUTHORIZED,
        statusCode: ErrorTypes.FORBIDDEN.errorStatus,
      };
    }
 
    const user = await prisma.user.findUnique({ where: { id: targetUserId } });
    if (!user) {
      return {
        success: false,
        message: 'User not found',
        messageKey: USER_FAVORITE_MESSAGE_KEYS.USER_NOT_FOUND,
        statusCode: ErrorTypes.NOT_FOUND.errorStatus,
      };
    }
 
    const recipe = await prisma.recipe.findUnique({ where: { id: recipeId } });
    if (!recipe) {
      return {
        success: false,
        message: 'Recipe not found',
        messageKey: USER_FAVORITE_MESSAGE_KEYS.RECIPE_NOT_FOUND,
        statusCode: ErrorTypes.NOT_FOUND.errorStatus,
      };
    }
 
    const alreadyFavorite = await prisma.user.findFirst({
      where: { id: targetUserId, favoriteRecipes: { some: { id: recipeId } } },
    });
 
    if (alreadyFavorite) {
      return {
        success: false,
        message: 'Recipe already in favorites',
        messageKey: USER_FAVORITE_MESSAGE_KEYS.ALREADY_FAVORITE,
        statusCode: ErrorTypes.BAD_REQUEST.errorStatus,
      };
    }
 
    await prisma.user.update({
      where: { id: targetUserId },
      data: { favoriteRecipes: { connect: { id: recipeId } } },
    });
 
    if (redis) {
      try {
        await redis.del(`user:${targetUserId}:favorites:all`);
      } catch (error) {
        console.error('Redis cache invalidation error:', error);
      }
    }
 
    return {
      success: true,
      message: 'Recipe successfully added to favorites',
      messageKey: USER_FAVORITE_MESSAGE_KEYS.SUCCESS,
      statusCode: 200,
    };
  },
 
  async removeFromFavoriteRecipes(
    currentUserId: string,
    currentUserRole: string,
    targetUserId: string,
    recipeId: string,
  ) {
    if (currentUserId !== targetUserId && currentUserRole !== 'ADMIN') {
      return {
        success: false,
        message: 'Unauthorized operation - insufficient permissions',
        messageKey: USER_FAVORITE_MESSAGE_KEYS.UNAUTHORIZED,
        statusCode: ErrorTypes.FORBIDDEN.errorStatus,
      };
    }
 
    const user = await prisma.user.findUnique({ where: { id: targetUserId } });
    if (!user) {
      return {
        success: false,
        message: 'User not found',
        messageKey: USER_FAVORITE_MESSAGE_KEYS.USER_NOT_FOUND,
        statusCode: ErrorTypes.NOT_FOUND.errorStatus,
      };
    }
 
    const recipe = await prisma.recipe.findUnique({ where: { id: recipeId } });
    if (!recipe) {
      return {
        success: false,
        message: 'Recipe not found',
        messageKey: USER_FAVORITE_MESSAGE_KEYS.RECIPE_NOT_FOUND,
        statusCode: ErrorTypes.NOT_FOUND.errorStatus,
      };
    }
 
    const alreadyFavorite = await prisma.user.findFirst({
      where: { id: targetUserId, favoriteRecipes: { some: { id: recipeId } } },
    });
 
    if (!alreadyFavorite) {
      return {
        success: false,
        message: 'Recipe not in favorites',
        messageKey: USER_FAVORITE_MESSAGE_KEYS.NOT_IN_FAVORITES,
        statusCode: ErrorTypes.BAD_REQUEST.errorStatus,
      };
    }
 
    await prisma.user.update({
      where: { id: targetUserId },
      data: { favoriteRecipes: { disconnect: { id: recipeId } } },
    });
 
    if (redis) {
      try {
        await redis.del(`user:${targetUserId}:favorites:all`);
      } catch (error) {
        console.error('Redis cache invalidation error:', error);
      }
    }
 
    return {
      success: true,
      message: 'Recipe successfully removed from favorites',
      messageKey: USER_FAVORITE_MESSAGE_KEYS.SUCCESS,
      statusCode: 200,
    };
  },
 
  async followUser(currentUserId: string, targetUserId: string) {
    if (currentUserId === targetUserId) {
      return {
        success: false,
        message: 'You cannot follow yourself',
        messageKey: USER_FOLLOW_MESSAGE_KEYS.CANNOT_FOLLOW_SELF,
        statusCode: ErrorTypes.BAD_REQUEST.errorStatus,
      };
    }
 
    const targetUser = await prisma.user.findUnique({
      where: { id: targetUserId },
    });
    if (!targetUser) {
      return {
        success: false,
        message: 'User not found',
        messageKey: USER_FOLLOW_MESSAGE_KEYS.USER_NOT_FOUND,
        statusCode: ErrorTypes.NOT_FOUND.errorStatus,
      };
    }
 
    const existingFollow = await prisma.follow.findUnique({
      where: {
        followerId_followingId: {
          followerId: currentUserId,
          followingId: targetUserId,
        },
      },
    });
 
    if (existingFollow) {
      return {
        success: false,
        message: 'Already following this user',
        messageKey: USER_FOLLOW_MESSAGE_KEYS.ALREADY_FOLLOWING,
        statusCode: ErrorTypes.BAD_REQUEST.errorStatus,
      };
    }
 
    await prisma.follow.create({
      data: { followerId: currentUserId, followingId: targetUserId },
    });
 
    if (redis) {
      try {
        await redis.del(`user:${currentUserId}:following:all`);
      } catch (error) {
        console.error('Redis cache invalidation error:', error);
      }
    }
 
    return {
      success: true,
      message: 'Successfully followed user',
      messageKey: USER_FOLLOW_MESSAGE_KEYS.FOLLOW_SUCCESS,
      statusCode: 200,
    };
  },
 
  async unfollowUser(currentUserId: string, targetUserId: string) {
    const existingFollow = await prisma.follow.findUnique({
      where: {
        followerId_followingId: {
          followerId: currentUserId,
          followingId: targetUserId,
        },
      },
    });
 
    if (!existingFollow) {
      return {
        success: false,
        message: 'You are not following this user',
        messageKey: USER_FOLLOW_MESSAGE_KEYS.NOT_FOLLOWING,
        statusCode: ErrorTypes.BAD_REQUEST.errorStatus,
      };
    }
 
    await prisma.follow.delete({
      where: {
        followerId_followingId: {
          followerId: currentUserId,
          followingId: targetUserId,
        },
      },
    });
 
    if (redis) {
      try {
        await redis.del(`user:${currentUserId}:following:all`);
      } catch (error) {
        console.error('Redis cache invalidation error:', error);
      }
    }
 
    return {
      success: true,
      message: 'Successfully unfollowed user',
      messageKey: USER_FOLLOW_MESSAGE_KEYS.UNFOLLOW_SUCCESS,
      statusCode: 200,
    };
  },
};