import { Types } from 'mongoose';
import { CommentsService } from './comments.service';

describe('CommentsService', () => {
  it('updates own comment and notifies newly mentioned users', async () => {
    const userId = new Types.ObjectId().toString();
    const postId = new Types.ObjectId().toString();
    const commentId = new Types.ObjectId().toString();
    const updatedContent = 'Edited comment @new_mention';

    const commentsRepository = {
      findById: jest.fn().mockResolvedValue({
        _id: new Types.ObjectId(commentId),
        authorId: new Types.ObjectId(userId),
        postId: new Types.ObjectId(postId),
        content: 'Original comment',
        mentionUsernames: ['old_mention'],
      }),
      updateById: jest.fn().mockResolvedValue({
        _id: new Types.ObjectId(commentId),
        authorId: new Types.ObjectId(userId),
        postId: new Types.ObjectId(postId),
        content: updatedContent,
        mentionUsernames: ['new_mention'],
      }),
    };
    const postsRepository = {
      findById: jest.fn(),
      setCommentsCount: jest.fn(),
    };
    const auditService = {
      logSuperAdminAction: jest.fn(),
    };
    const feedVersionService = {
      bumpGlobalVersion: jest.fn(),
    };
    const notificationsService = {
      createCommentNotification: jest.fn(),
      createMentionNotification: jest.fn(),
    };
    const usersRepository = {
      findByUsernames: jest.fn().mockResolvedValue([{ id: 'mentioned-user-id', username: 'new_mention' }]),
    };
    const followsRepository = {
      findOne: jest.fn(),
    };

    const service = new CommentsService(
      commentsRepository as any,
      postsRepository as any,
      auditService as any,
      feedVersionService as any,
      notificationsService as any,
      usersRepository as any,
      followsRepository as any,
    );

    const result = await service.update(userId, commentId, {
      content: updatedContent,
      mentionUsernames: ['new_mention'],
    });

    expect(commentsRepository.updateById).toHaveBeenCalledWith(commentId, {
      content: updatedContent,
      mentionUsernames: ['new_mention'],
    });
    expect(feedVersionService.bumpGlobalVersion).toHaveBeenCalled();
    expect(notificationsService.createMentionNotification).toHaveBeenCalledWith(
      userId,
      'mentioned-user-id',
      postId,
      {
        resourceType: 'comment',
        previewText: updatedContent,
        deepLink: `/posts/${postId}`,
      },
    );
    expect(result).toEqual(
      expect.objectContaining({
        content: updatedContent,
        mentionUsernames: ['new_mention'],
      }),
    );
  });
});
