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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
import { nanoid } from 'nanoid';
import mongoose from 'mongoose';
import { Constants } from 'librechat-data-provider';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { createShareMethods, type ShareMethods } from './share';
import type { SchemaWithMeiliMethods } from '~/models/plugins/mongoMeili';
import type * as t from '~/types';

describe('Share Methods', () => {
  let mongoServer: MongoMemoryServer;
  let shareMethods: ShareMethods;
  let SharedLink: mongoose.Model<t.ISharedLink>;
  let Message: mongoose.Model<t.IMessage>;
  let Conversation: SchemaWithMeiliMethods;

  beforeAll(async () => {
    mongoServer = await MongoMemoryServer.create();
    const mongoUri = mongoServer.getUri();
    await mongoose.connect(mongoUri);

    // Create schemas
    const sharedLinkSchema = new mongoose.Schema<t.ISharedLink>(
      {
        conversationId: { type: String, required: true },
        title: { type: String, index: true },
        user: { type: String, index: true },
        messages: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Message' }],
        shareId: { type: String, index: true },
        isPublic: { type: Boolean, default: true },
      },
      { timestamps: true },
    );

    const messageSchema = new mongoose.Schema<t.IMessage>(
      {
        messageId: { type: String, required: true },
        conversationId: { type: String, required: true },
        user: { type: String, required: true },
        text: String,
        isCreatedByUser: Boolean,
        model: String,
        parentMessageId: String,
        attachments: [mongoose.Schema.Types.Mixed],
        content: [mongoose.Schema.Types.Mixed],
      },
      { timestamps: true },
    );

    const conversationSchema = new mongoose.Schema<t.IConversation>(
      {
        conversationId: { type: String, required: true },
        title: String,
        user: String,
      },
      { timestamps: true },
    );

    // Register models
    SharedLink =
      mongoose.models.SharedLink || mongoose.model<t.ISharedLink>('SharedLink', sharedLinkSchema);
    Message = mongoose.models.Message || mongoose.model<t.IMessage>('Message', messageSchema);
    Conversation = (mongoose.models.Conversation ||
      mongoose.model<t.IConversation>(
        'Conversation',
        conversationSchema,
      )) as SchemaWithMeiliMethods;

    // Create share methods
    shareMethods = createShareMethods(mongoose);
  });

  afterAll(async () => {
    await mongoose.disconnect();
    await mongoServer.stop();
  });

  beforeEach(async () => {
    await SharedLink.deleteMany({});
    await Message.deleteMany({});
    await Conversation.deleteMany({});
  });

  describe('createSharedLink', () => {
    test('should create a new shared link', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;

      // Create test conversation
      await Conversation.create({
        conversationId,
        title: 'Test Conversation',
        user: userId,
      });

      // Create test messages
      await Message.create([
        {
          messageId: `msg_${nanoid()}`,
          conversationId,
          user: userId,
          text: 'Hello',
          isCreatedByUser: true,
        },
        {
          messageId: `msg_${nanoid()}`,
          conversationId,
          user: userId,
          text: 'World',
          isCreatedByUser: false,
          model: 'gpt-4',
        },
      ]);

      const result = await shareMethods.createSharedLink(userId, conversationId);

      expect(result).toBeDefined();
      expect(result.shareId).toBeDefined();
      expect(result.conversationId).toBe(conversationId);

      // Verify the share was created in the database
      const savedShare = await SharedLink.findOne({ shareId: result.shareId });
      expect(savedShare).toBeDefined();
      expect(savedShare?.user).toBe(userId);
      expect(savedShare?.title).toBe('Test Conversation');
      expect(savedShare?.messages).toHaveLength(2);
    });

    test('should throw error if share already exists', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;

      await Conversation.create({
        conversationId,
        title: 'Test Conversation',
        user: userId,
      });

      // Create messages so we can create a share
      await Message.create({
        messageId: `msg_${nanoid()}`,
        conversationId,
        user: userId,
        text: 'Test message',
        isCreatedByUser: true,
      });

      // Create first share
      await shareMethods.createSharedLink(userId, conversationId);

      // Try to create duplicate
      await expect(shareMethods.createSharedLink(userId, conversationId)).rejects.toThrow(
        'Share already exists',
      );
    });

    test('should throw error with missing parameters', async () => {
      await expect(shareMethods.createSharedLink('', 'conv123')).rejects.toThrow(
        'Missing required parameters',
      );

      await expect(shareMethods.createSharedLink('user123', '')).rejects.toThrow(
        'Missing required parameters',
      );
    });

    test('should only include messages from the same user', async () => {
      const userId1 = new mongoose.Types.ObjectId().toString();
      const userId2 = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;

      await Conversation.create({
        conversationId,
        title: 'Test Conversation',
        user: userId1,
      });

      // Create messages from different users
      await Message.create([
        {
          messageId: `msg_${nanoid()}`,
          conversationId,
          user: userId1,
          text: 'User 1 message',
          isCreatedByUser: true,
        },
        {
          messageId: `msg_${nanoid()}`,
          conversationId,
          user: userId2,
          text: 'User 2 message',
          isCreatedByUser: true,
        },
      ]);

      const result = await shareMethods.createSharedLink(userId1, conversationId);

      const savedShare = await SharedLink.findOne({ shareId: result.shareId }).populate('messages');
      expect(savedShare?.messages).toHaveLength(1);
      expect((savedShare?.messages?.[0] as unknown as t.IMessage | undefined)?.text).toBe(
        'User 1 message',
      );
    });

    test('should not allow user to create shared link for conversation they do not own', async () => {
      const ownerUserId = new mongoose.Types.ObjectId().toString();
      const otherUserId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;

      // Create conversation owned by ownerUserId
      await Conversation.create({
        conversationId,
        title: 'Owner Conversation',
        user: ownerUserId,
      });

      // Create messages for the conversation
      await Message.create([
        {
          messageId: `msg_${nanoid()}`,
          conversationId,
          user: ownerUserId,
          text: 'Owner message',
          isCreatedByUser: true,
        },
      ]);

      // Try to create a shared link as a different user
      await expect(shareMethods.createSharedLink(otherUserId, conversationId)).rejects.toThrow(
        'Conversation not found or access denied',
      );

      // Verify no share was created
      const shares = await SharedLink.find({ conversationId });
      expect(shares).toHaveLength(0);
    });

    test('should not allow creating share for conversation with no messages', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;

      // Create conversation without any messages
      await Conversation.create({
        conversationId,
        title: 'Empty Conversation',
        user: userId,
      });

      // Try to create a shared link for conversation with no messages
      await expect(shareMethods.createSharedLink(userId, conversationId)).rejects.toThrow(
        'No messages to share',
      );

      // Verify no share was created
      const shares = await SharedLink.find({ conversationId });
      expect(shares).toHaveLength(0);
    });
  });

  describe('getSharedMessages', () => {
    test('should retrieve and anonymize shared messages', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;
      const shareId = `share_${nanoid()}`;

      // Create messages
      const messages = await Message.create([
        {
          messageId: `msg_${nanoid()}`,
          conversationId,
          user: userId,
          text: 'Hello',
          isCreatedByUser: true,
          parentMessageId: Constants.NO_PARENT,
        },
        {
          messageId: `msg_${nanoid()}`,
          conversationId,
          user: userId,
          text: 'World',
          isCreatedByUser: false,
          model: 'gpt-4',
          parentMessageId: Constants.NO_PARENT,
        },
      ]);

      // Create shared link
      await SharedLink.create({
        shareId,
        conversationId,
        user: userId,
        title: 'Test Share',
        messages: messages.map((m) => m._id),
        isPublic: true,
      });

      const result = await shareMethods.getSharedMessages(shareId);

      expect(result).toBeDefined();
      expect(result?.shareId).toBe(shareId);
      expect(result?.conversationId).not.toBe(conversationId); // Should be anonymized
      expect(result?.messages).toHaveLength(2);

      // Check anonymization
      result?.messages.forEach((msg) => {
        expect(msg.messageId).toMatch(/^msg_/); // Should be anonymized with msg_ prefix
        expect(msg.messageId).not.toBe(messages[0].messageId); // Should be different from original
        expect(msg.conversationId).toBe(result.conversationId);
        expect(msg.user).toBeUndefined(); // User should be removed
      });
    });

    test('should return null for non-public share', async () => {
      const shareId = `share_${nanoid()}`;

      await SharedLink.create({
        shareId,
        conversationId: 'conv123',
        user: 'user123',
        isPublic: false,
      });

      const result = await shareMethods.getSharedMessages(shareId);
      expect(result).toBeNull();
    });

    test('should return null for non-existent share', async () => {
      const result = await shareMethods.getSharedMessages('non_existent_share');
      expect(result).toBeNull();
    });

    test('should handle messages with attachments', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;
      const shareId = `share_${nanoid()}`;

      const message = await Message.create({
        messageId: `msg_${nanoid()}`,
        conversationId,
        user: userId,
        text: 'Message with attachment',
        isCreatedByUser: true,
        attachments: [
          {
            file_id: 'file123',
            filename: 'test.pdf',
            type: 'application/pdf',
          },
        ],
      });

      await SharedLink.create({
        shareId,
        conversationId,
        user: userId,
        messages: [message._id],
        isPublic: true,
      });

      const result = await shareMethods.getSharedMessages(shareId);

      expect(result?.messages[0].attachments).toHaveLength(1);
      expect(
        (result?.messages[0].attachments?.[0] as unknown as t.IMessage | undefined)?.messageId,
      ).toBe(result?.messages[0].messageId);
      expect(
        (result?.messages[0].attachments?.[0] as unknown as t.IMessage | undefined)?.conversationId,
      ).toBe(result?.conversationId);
    });
  });

  describe('getSharedLinks', () => {
    test('should retrieve paginated shared links for a user', async () => {
      const userId = new mongoose.Types.ObjectId().toString();

      // Create multiple shared links
      const sharePromises = Array.from({ length: 15 }, (_, i) =>
        SharedLink.create({
          shareId: `share_${i}`,
          conversationId: `conv_${i}`,
          user: userId,
          title: `Share ${i}`,
          isPublic: true,
          createdAt: new Date(Date.now() - i * 1000 * 60), // Different timestamps
        }),
      );

      await Promise.all(sharePromises);

      const result = await shareMethods.getSharedLinks(userId, undefined, 10);

      expect(result.links).toHaveLength(10);
      expect(result.hasNextPage).toBe(true);
      expect(result.nextCursor).toBeDefined();

      // Check ordering (newest first by default)
      expect(result.links[0].title).toBe('Share 0');
      expect(result.links[9].title).toBe('Share 9');
    });

    test('should filter by isPublic parameter', async () => {
      const userId = new mongoose.Types.ObjectId().toString();

      await SharedLink.create([
        {
          shareId: 'public_share',
          conversationId: 'conv1',
          user: userId,
          title: 'Public Share',
          isPublic: true,
        },
        {
          shareId: 'private_share',
          conversationId: 'conv2',
          user: userId,
          title: 'Private Share',
          isPublic: false,
        },
      ]);

      const publicResults = await shareMethods.getSharedLinks(userId, undefined, 10, true);
      const privateResults = await shareMethods.getSharedLinks(userId, undefined, 10, false);

      expect(publicResults.links).toHaveLength(1);
      expect(publicResults.links[0].title).toBe('Public Share');

      expect(privateResults.links).toHaveLength(1);
      expect(privateResults.links[0].title).toBe('Private Share');
    });

    test('should handle search with mocked meiliSearch and user filter', async () => {
      const userId = new mongoose.Types.ObjectId().toString();

      // Mock meiliSearch method
      const meiliSearchMock = jest.fn().mockResolvedValue({
        hits: [{ conversationId: 'conv1' }],
      });
      Conversation.meiliSearch = meiliSearchMock;

      await SharedLink.create([
        {
          shareId: 'share1',
          conversationId: 'conv1',
          user: userId,
          title: 'Matching Share',
          isPublic: true,
        },
        {
          shareId: 'share2',
          conversationId: 'conv2',
          user: userId,
          title: 'Non-matching Share',
          isPublic: true,
        },
      ]);

      const result = await shareMethods.getSharedLinks(
        userId,
        undefined,
        10,
        true,
        'createdAt',
        'desc',
        'search term',
      );

      expect(result.links).toHaveLength(1);
      expect(result.links[0].title).toBe('Matching Share');

      // Verify that meiliSearch was called with the correct user filter
      expect(meiliSearchMock).toHaveBeenCalledWith('search term', { filter: `user = "${userId}"` });
    });

    test('should handle empty results', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const result = await shareMethods.getSharedLinks(userId);

      expect(result.links).toHaveLength(0);
      expect(result.hasNextPage).toBe(false);
      expect(result.nextCursor).toBeUndefined();
    });

    test('should only return shares from search results for the current user', async () => {
      const userId1 = new mongoose.Types.ObjectId().toString();
      const userId2 = new mongoose.Types.ObjectId().toString();

      // Mock meiliSearch to simulate finding conversations from both users
      const meiliSearchMock = jest.fn().mockImplementation((searchTerm, params) => {
        // Simulate MeiliSearch filtering by user
        const filter = params?.filter;
        if (filter && filter.includes(userId1)) {
          return Promise.resolve({
            hits: [{ conversationId: 'conv1' }, { conversationId: 'conv3' }],
          });
        } else if (filter && filter.includes(userId2)) {
          return Promise.resolve({ hits: [{ conversationId: 'conv2' }] });
        }
        // Without filter, would return all conversations (security issue)
        return Promise.resolve({
          hits: [
            { conversationId: 'conv1' },
            { conversationId: 'conv2' },
            { conversationId: 'conv3' },
          ],
        });
      });
      Conversation.meiliSearch = meiliSearchMock;

      // Create shares for different users
      await SharedLink.create([
        {
          shareId: 'share1',
          conversationId: 'conv1',
          user: userId1,
          title: 'User 1 Share',
          isPublic: true,
        },
        {
          shareId: 'share2',
          conversationId: 'conv2',
          user: userId2,
          title: 'User 2 Share',
          isPublic: true,
        },
        {
          shareId: 'share3',
          conversationId: 'conv3',
          user: userId1,
          title: 'Another User 1 Share',
          isPublic: true,
        },
      ]);

      // Search as userId1
      const result1 = await shareMethods.getSharedLinks(
        userId1,
        undefined,
        10,
        true,
        'createdAt',
        'desc',
        'search term',
      );

      // Should only get shares from conversations belonging to userId1
      expect(result1.links).toHaveLength(2);
      expect(result1.links.every((link) => link.title.includes('User 1'))).toBe(true);

      // Verify correct filter was used
      expect(meiliSearchMock).toHaveBeenCalledWith('search term', {
        filter: `user = "${userId1}"`,
      });

      // Search as userId2
      const result2 = await shareMethods.getSharedLinks(
        userId2,
        undefined,
        10,
        true,
        'createdAt',
        'desc',
        'search term',
      );

      // Should only get shares from conversations belonging to userId2
      expect(result2.links).toHaveLength(1);
      expect(result2.links[0].title).toBe('User 2 Share');

      // Verify correct filter was used for second user
      expect(meiliSearchMock).toHaveBeenCalledWith('search term', {
        filter: `user = "${userId2}"`,
      });
    });

    test('should only return shares for the specified user', async () => {
      const userId1 = new mongoose.Types.ObjectId().toString();
      const userId2 = new mongoose.Types.ObjectId().toString();

      // Create shares for different users
      await SharedLink.create([
        {
          shareId: 'share1',
          conversationId: 'conv1',
          user: userId1,
          title: 'User 1 Share',
          isPublic: true,
        },
        {
          shareId: 'share2',
          conversationId: 'conv2',
          user: userId2,
          title: 'User 2 Share',
          isPublic: true,
        },
        {
          shareId: 'share3',
          conversationId: 'conv3',
          user: userId1,
          title: 'Another User 1 Share',
          isPublic: true,
        },
      ]);

      const result1 = await shareMethods.getSharedLinks(userId1);
      const result2 = await shareMethods.getSharedLinks(userId2);

      expect(result1.links).toHaveLength(2);
      expect(result1.links.every((link) => link.title.includes('User 1'))).toBe(true);

      expect(result2.links).toHaveLength(1);
      expect(result2.links[0].title).toBe('User 2 Share');
    });
  });

  describe('updateSharedLink', () => {
    test('should update shared link with new messages', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;
      const oldShareId = `share_${nanoid()}`;

      // Create initial messages
      const initialMessages = await Message.create([
        {
          messageId: `msg_1`,
          conversationId,
          user: userId,
          text: 'Initial message',
          isCreatedByUser: true,
        },
      ]);

      // Create shared link
      await SharedLink.create({
        shareId: oldShareId,
        conversationId,
        user: userId,
        messages: initialMessages.map((m) => m._id),
        isPublic: true,
      });

      // Add new message
      await Message.create({
        messageId: `msg_2`,
        conversationId,
        user: userId,
        text: 'New message',
        isCreatedByUser: false,
      });

      const result = await shareMethods.updateSharedLink(userId, oldShareId);

      expect(result.shareId).not.toBe(oldShareId); // Should generate new shareId
      expect(result.conversationId).toBe(conversationId);

      // Verify updated share
      const updatedShare = await SharedLink.findOne({ shareId: result.shareId }).populate(
        'messages',
      );
      expect(updatedShare?.messages).toHaveLength(2);
    });

    test('should throw error if share not found', async () => {
      await expect(shareMethods.updateSharedLink('user123', 'non_existent')).rejects.toThrow(
        'Share not found',
      );
    });

    test('should throw error with missing parameters', async () => {
      await expect(shareMethods.updateSharedLink('', 'share123')).rejects.toThrow(
        'Missing required parameters',
      );
    });

    test('should only update with messages from the same user', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const otherUserId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;
      const shareId = `share_${nanoid()}`;

      // Create initial share
      await SharedLink.create({
        shareId,
        conversationId,
        user: userId,
        messages: [],
        isPublic: true,
      });

      // Add messages from different users
      await Message.create([
        {
          messageId: `msg_1`,
          conversationId,
          user: userId,
          text: 'User message',
          isCreatedByUser: true,
        },
        {
          messageId: `msg_2`,
          conversationId,
          user: otherUserId,
          text: 'Other user message',
          isCreatedByUser: true,
        },
      ]);

      const result = await shareMethods.updateSharedLink(userId, shareId);

      const updatedShare = await SharedLink.findOne({ shareId: result.shareId }).populate(
        'messages',
      );
      expect(updatedShare?.messages).toHaveLength(1);
      expect((updatedShare?.messages?.[0] as unknown as t.IMessage | undefined)?.text).toBe(
        'User message',
      );
    });

    test('should not allow user to update shared link they do not own', async () => {
      const ownerUserId = new mongoose.Types.ObjectId().toString();
      const otherUserId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;
      const shareId = `share_${nanoid()}`;

      // Create shared link owned by ownerUserId
      await SharedLink.create({
        shareId,
        conversationId,
        user: ownerUserId,
        messages: [],
        isPublic: true,
      });

      // Try to update as a different user
      await expect(shareMethods.updateSharedLink(otherUserId, shareId)).rejects.toThrow(
        'Share not found',
      );

      // Verify the original share still exists and is unchanged
      const originalShare = await SharedLink.findOne({ shareId });
      expect(originalShare).toBeDefined();
      expect(originalShare?.user).toBe(ownerUserId);
    });
  });

  describe('deleteSharedLink', () => {
    test('should delete shared link', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const shareId = `share_${nanoid()}`;

      await SharedLink.create({
        shareId,
        conversationId: 'conv123',
        user: userId,
        isPublic: true,
      });

      const result = await shareMethods.deleteSharedLink(userId, shareId);

      expect(result).toBeDefined();
      expect(result?.success).toBe(true);
      expect(result?.shareId).toBe(shareId);

      // Verify deletion
      const deletedShare = await SharedLink.findOne({ shareId });
      expect(deletedShare).toBeNull();
    });

    test('should return null if share not found', async () => {
      const result = await shareMethods.deleteSharedLink('user123', 'non_existent');
      expect(result).toBeNull();
    });

    test('should not delete share from different user', async () => {
      const userId1 = new mongoose.Types.ObjectId().toString();
      const userId2 = new mongoose.Types.ObjectId().toString();
      const shareId = `share_${nanoid()}`;

      await SharedLink.create({
        shareId,
        conversationId: 'conv123',
        user: userId1,
        isPublic: true,
      });

      const result = await shareMethods.deleteSharedLink(userId2, shareId);
      expect(result).toBeNull();

      // Verify share still exists
      const share = await SharedLink.findOne({ shareId });
      expect(share).toBeDefined();
    });

    test('should handle missing parameters for deleteSharedLink', async () => {
      await expect(shareMethods.deleteSharedLink('', 'share123')).rejects.toThrow(
        'Missing required parameters',
      );

      await expect(shareMethods.deleteSharedLink('user123', '')).rejects.toThrow(
        'Missing required parameters',
      );
    });
  });

  describe('getSharedLink', () => {
    test('should retrieve existing shared link', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;
      const shareId = `share_${nanoid()}`;

      await SharedLink.create({
        shareId,
        conversationId,
        user: userId,
        isPublic: true,
      });

      const result = await shareMethods.getSharedLink(userId, conversationId);

      expect(result.success).toBe(true);
      expect(result.shareId).toBe(shareId);
    });

    test('should return null shareId if not found', async () => {
      const result = await shareMethods.getSharedLink('user123', 'conv123');

      expect(result.success).toBe(false);
      expect(result.shareId).toBeNull();
    });

    test('should not return share from different user', async () => {
      const userId1 = new mongoose.Types.ObjectId().toString();
      const userId2 = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;

      await SharedLink.create({
        shareId: 'share123',
        conversationId,
        user: userId1,
        isPublic: true,
      });

      const result = await shareMethods.getSharedLink(userId2, conversationId);

      expect(result.success).toBe(false);
      expect(result.shareId).toBeNull();
    });

    test('should handle missing parameters for getSharedLink', async () => {
      await expect(shareMethods.getSharedLink('', 'conv123')).rejects.toThrow(
        'Missing required parameters',
      );

      await expect(shareMethods.getSharedLink('user123', '')).rejects.toThrow(
        'Missing required parameters',
      );
    });

    test('should only return public shares', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;
      const shareId = `share_${nanoid()}`;

      // Create a non-public share
      await SharedLink.create({
        shareId,
        conversationId,
        user: userId,
        isPublic: false,
      });

      const result = await shareMethods.getSharedLink(userId, conversationId);

      expect(result.success).toBe(false);
      expect(result.shareId).toBeNull();
    });
  });

  describe('deleteAllSharedLinks', () => {
    test('should delete all shared links for a user', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const otherUserId = new mongoose.Types.ObjectId().toString();

      // Create shares for different users
      await SharedLink.create([
        { shareId: 'share1', conversationId: 'conv1', user: userId },
        { shareId: 'share2', conversationId: 'conv2', user: userId },
        { shareId: 'share3', conversationId: 'conv3', user: otherUserId },
      ]);

      const result = await shareMethods.deleteAllSharedLinks(userId);

      expect(result.deletedCount).toBe(2);
      expect(result.message).toContain('successfully');

      // Verify only user's shares were deleted
      const remainingShares = await SharedLink.find({});
      expect(remainingShares).toHaveLength(1);
      expect(remainingShares[0].user).toBe(otherUserId);
    });

    test('should handle when no shares exist', async () => {
      const result = await shareMethods.deleteAllSharedLinks('user123');

      expect(result.deletedCount).toBe(0);
      expect(result.message).toContain('successfully');
    });

    test('should only delete shares belonging to the specified user', async () => {
      const userId1 = new mongoose.Types.ObjectId().toString();
      const userId2 = new mongoose.Types.ObjectId().toString();
      const userId3 = new mongoose.Types.ObjectId().toString();

      // Create multiple shares for different users
      await SharedLink.create([
        { shareId: 'share1', conversationId: 'conv1', user: userId1, isPublic: true },
        { shareId: 'share2', conversationId: 'conv2', user: userId1, isPublic: false },
        { shareId: 'share3', conversationId: 'conv3', user: userId2, isPublic: true },
        { shareId: 'share4', conversationId: 'conv4', user: userId2, isPublic: true },
        { shareId: 'share5', conversationId: 'conv5', user: userId3, isPublic: true },
      ]);

      // Delete all shares for userId1
      const result = await shareMethods.deleteAllSharedLinks(userId1);
      expect(result.deletedCount).toBe(2);

      // Verify shares for other users still exist
      const remainingShares = await SharedLink.find({});
      expect(remainingShares).toHaveLength(3);
      expect(remainingShares.every((share) => share.user !== userId1)).toBe(true);

      // Verify specific users' shares remain
      const user2Shares = await SharedLink.find({ user: userId2 });
      expect(user2Shares).toHaveLength(2);

      const user3Shares = await SharedLink.find({ user: userId3 });
      expect(user3Shares).toHaveLength(1);
    });
  });

  describe('deleteConvoSharedLink', () => {
    test('should delete all shared links for a specific conversation', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId1 = 'conv-to-delete';
      const conversationId2 = 'conv-to-keep';

      await SharedLink.create([
        { shareId: 'share1', conversationId: conversationId1, user: userId, isPublic: true },
        { shareId: 'share2', conversationId: conversationId1, user: userId, isPublic: false },
        { shareId: 'share3', conversationId: conversationId2, user: userId, isPublic: true },
      ]);

      const result = await shareMethods.deleteConvoSharedLink(userId, conversationId1);

      expect(result.deletedCount).toBe(2);
      expect(result.message).toContain('successfully');

      const remainingShares = await SharedLink.find({});
      expect(remainingShares).toHaveLength(1);
      expect(remainingShares[0].conversationId).toBe(conversationId2);
    });

    test('should only delete shares for the specified user and conversation', async () => {
      const userId1 = new mongoose.Types.ObjectId().toString();
      const userId2 = new mongoose.Types.ObjectId().toString();
      const conversationId = 'shared-conv';

      await SharedLink.create([
        { shareId: 'share1', conversationId, user: userId1, isPublic: true },
        { shareId: 'share2', conversationId, user: userId2, isPublic: true },
        { shareId: 'share3', conversationId: 'other-conv', user: userId1, isPublic: true },
      ]);

      const result = await shareMethods.deleteConvoSharedLink(userId1, conversationId);

      expect(result.deletedCount).toBe(1);

      const remainingShares = await SharedLink.find({});
      expect(remainingShares).toHaveLength(2);
      expect(
        remainingShares.some((s) => s.user === userId2 && s.conversationId === conversationId),
      ).toBe(true);
      expect(
        remainingShares.some((s) => s.user === userId1 && s.conversationId === 'other-conv'),
      ).toBe(true);
    });

    test('should handle when no shares exist for the conversation', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = 'nonexistent-conv';

      const result = await shareMethods.deleteConvoSharedLink(userId, conversationId);

      expect(result.deletedCount).toBe(0);
      expect(result.message).toContain('successfully');
    });

    test('should throw error when userId is missing', async () => {
      await expect(shareMethods.deleteConvoSharedLink('', 'conv123')).rejects.toThrow(
        'Missing required parameters',
      );
    });

    test('should throw error when conversationId is missing', async () => {
      await expect(shareMethods.deleteConvoSharedLink('user123', '')).rejects.toThrow(
        'Missing required parameters',
      );
    });

    test('should delete multiple shared links for same conversation', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = 'conv-with-many-shares';

      await SharedLink.create([
        { shareId: 'share1', conversationId, user: userId, isPublic: true },
        {
          shareId: 'share2',
          conversationId,
          user: userId,
          isPublic: true,
          targetMessageId: 'msg1',
        },
        {
          shareId: 'share3',
          conversationId,
          user: userId,
          isPublic: true,
          targetMessageId: 'msg2',
        },
        { shareId: 'share4', conversationId, user: userId, isPublic: false },
      ]);

      const result = await shareMethods.deleteConvoSharedLink(userId, conversationId);

      expect(result.deletedCount).toBe(4);

      const remainingShares = await SharedLink.find({ conversationId, user: userId });
      expect(remainingShares).toHaveLength(0);
    });
  });

  describe('Edge Cases and Error Handling', () => {
    test('should handle conversation with special characters in ID', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = 'conv|with|pipes';

      await Conversation.create({
        conversationId,
        title: 'Special Conversation',
        user: userId,
      });

      // Create a message so we can create a share
      await Message.create({
        messageId: `msg_${nanoid()}`,
        conversationId,
        user: userId,
        text: 'Test message',
        isCreatedByUser: true,
      });

      const result = await shareMethods.createSharedLink(userId, conversationId);

      expect(result).toBeDefined();
      expect(result.conversationId).toBe(conversationId);
    });

    test('should handle messages with assistant_id', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;
      const shareId = `share_${nanoid()}`;

      const message = await Message.create({
        messageId: `msg_${nanoid()}`,
        conversationId,
        user: userId,
        text: 'Assistant message',
        isCreatedByUser: false,
        model: 'asst_123456',
      });

      await SharedLink.create({
        shareId,
        conversationId,
        user: userId,
        messages: [message._id],
        isPublic: true,
      });

      const result = await shareMethods.getSharedMessages(shareId);

      expect(result?.messages[0].model).toMatch(/^a_/); // Should be anonymized
    });

    test('should handle concurrent operations', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationIds = Array.from({ length: 5 }, () => `conv_${nanoid()}`);

      // Create conversations and messages
      await Promise.all(
        conversationIds.map(async (id) => {
          await Conversation.create({
            conversationId: id,
            title: `Conversation ${id}`,
            user: userId,
          });
          // Create a message for each conversation
          await Message.create({
            messageId: `msg_${nanoid()}`,
            conversationId: id,
            user: userId,
            text: `Message for ${id}`,
            isCreatedByUser: true,
          });
        }),
      );

      // Concurrent share creation
      const createPromises = conversationIds.map((id) => shareMethods.createSharedLink(userId, id));

      const results = await Promise.all(createPromises);

      expect(results).toHaveLength(5);
      results.forEach((result, index) => {
        expect(result.shareId).toBeDefined();
        expect(result.conversationId).toBe(conversationIds[index]);
      });
    });

    test('should handle database errors gracefully', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;

      // Create conversation and message first
      await Conversation.create({
        conversationId,
        title: 'Test Conversation',
        user: userId,
      });

      await Message.create({
        messageId: `msg_${nanoid()}`,
        conversationId,
        user: userId,
        text: 'Test message',
        isCreatedByUser: true,
      });

      // Mock a database error
      const originalCreate = SharedLink.create;
      SharedLink.create = jest.fn().mockRejectedValue(new Error('Database error'));

      await expect(shareMethods.createSharedLink(userId, conversationId)).rejects.toThrow(
        'Error creating shared link',
      );

      SharedLink.create = originalCreate;
    });
  });

  describe('Anonymization', () => {
    beforeEach(() => {
      // Ensure any mocks are restored before each test
      jest.restoreAllMocks();
    });

    test('should consistently anonymize IDs', async () => {
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;
      const shareId = `share_${nanoid()}`;
      const messageId1 = `msg_${nanoid()}`;
      const messageId2 = `msg_${nanoid()}`;

      const messages = await Message.create([
        {
          messageId: messageId1,
          conversationId,
          user: userId,
          text: 'First message',
          isCreatedByUser: true,
          parentMessageId: Constants.NO_PARENT,
        },
        {
          messageId: messageId2,
          conversationId,
          user: userId,
          text: 'Second message',
          isCreatedByUser: false,
          parentMessageId: messageId1, // Reference to first message
        },
      ]);

      await SharedLink.create({
        shareId,
        conversationId,
        user: userId,
        messages: messages.map((m) => m._id),
        isPublic: true,
      });

      const result = await shareMethods.getSharedMessages(shareId);

      // Check that anonymization is consistent within the same result
      expect(result?.messages).toHaveLength(2);

      // The second message's parentMessageId should match the first message's anonymized ID
      expect(result?.messages[1].parentMessageId).toBe(result?.messages[0].messageId);

      // Both messages should have the same anonymized conversationId
      expect(result?.messages[0].conversationId).toBe(result?.conversationId);
      expect(result?.messages[1].conversationId).toBe(result?.conversationId);
    });

    test('should handle NO_PARENT constant correctly', async () => {
      const { Constants } = await import('librechat-data-provider');
      const userId = new mongoose.Types.ObjectId().toString();
      const conversationId = `conv_${nanoid()}`;
      const shareId = `share_${nanoid()}`;

      const message = await Message.create({
        messageId: `msg_${nanoid()}`,
        conversationId,
        user: userId,
        text: 'Root message',
        isCreatedByUser: true,
        parentMessageId: Constants.NO_PARENT,
      });

      await SharedLink.create({
        shareId,
        conversationId,
        user: userId,
        messages: [message._id],
        isPublic: true,
      });

      const result = await shareMethods.getSharedMessages(shareId);

      expect(result?.messages[0].parentMessageId).toBe(Constants.NO_PARENT);
    });
  });
});