aboutsummaryrefslogtreecommitdiffstats
path: root/packages/trpc/models/lists.ts
blob: 0968492a90986cecf8fa5c48d6c26cffd4a11994 (plain) (blame)
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
import crypto from "node:crypto";
import { TRPCError } from "@trpc/server";
import { and, count, eq, inArray, or } from "drizzle-orm";
import invariant from "tiny-invariant";
import { z } from "zod";

import { SqliteError } from "@karakeep/db";
import {
  bookmarkLists,
  bookmarksInLists,
  listCollaborators,
  users,
} from "@karakeep/db/schema";
import { triggerRuleEngineOnEvent } from "@karakeep/shared-server";
import { parseSearchQuery } from "@karakeep/shared/searchQueryParser";
import { ZSortOrder } from "@karakeep/shared/types/bookmarks";
import {
  ZBookmarkList,
  zEditBookmarkListSchemaWithValidation,
  zNewBookmarkListSchema,
} from "@karakeep/shared/types/lists";
import { ZCursor } from "@karakeep/shared/types/pagination";
import { switchCase } from "@karakeep/shared/utils/switch";

import { AuthedContext, Context } from "..";
import { buildImpersonatingAuthedContext } from "../lib/impersonate";
import { getBookmarkIdsFromMatcher } from "../lib/search";
import { Bookmark } from "./bookmarks";
import { ListInvitation } from "./listInvitations";

interface ListCollaboratorEntry {
  membershipId: string;
}

export abstract class List {
  protected constructor(
    protected ctx: AuthedContext,
    protected list: ZBookmarkList & { userId: string },
  ) {}

  get id() {
    return this.list.id;
  }

  asZBookmarkList() {
    if (this.list.userId === this.ctx.user.id) {
      return this.list;
    }

    // There's some privacy implications here, so we need to think twice
    // about the values that we return.
    return {
      id: this.list.id,
      name: this.list.name,
      description: this.list.description,
      userId: this.list.userId,
      icon: this.list.icon,
      type: this.list.type,
      query: this.list.query,
      userRole: this.list.userRole,
      hasCollaborators: this.list.hasCollaborators,

      // Hide parentId as it is not relevant to the user
      parentId: null,
      // Hide whether the list is public or not.
      public: false,
    };
  }

  private static fromData(
    ctx: AuthedContext,
    data: ZBookmarkList & { userId: string },
    collaboratorEntry: ListCollaboratorEntry | null,
  ) {
    if (data.type === "smart") {
      return new SmartList(ctx, data);
    } else {
      return new ManualList(ctx, data, collaboratorEntry);
    }
  }

  static async fromId(
    ctx: AuthedContext,
    id: string,
  ): Promise<ManualList | SmartList> {
    // First try to find the list owned by the user
    let list = await (async (): Promise<
      (ZBookmarkList & { userId: string }) | undefined
    > => {
      const l = await ctx.db.query.bookmarkLists.findFirst({
        columns: {
          rssToken: false,
        },
        where: and(
          eq(bookmarkLists.id, id),
          eq(bookmarkLists.userId, ctx.user.id),
        ),
        with: {
          collaborators: {
            columns: {
              id: true,
            },
            limit: 1,
          },
        },
      });
      return l
        ? {
            ...l,
            userRole: "owner",
            hasCollaborators: l.collaborators.length > 0,
          }
        : l;
    })();

    // If not found, check if the user is a collaborator
    let collaboratorEntry: ListCollaboratorEntry | null = null;
    if (!list) {
      const collaborator = await ctx.db.query.listCollaborators.findFirst({
        where: and(
          eq(listCollaborators.listId, id),
          eq(listCollaborators.userId, ctx.user.id),
        ),
        with: {
          list: {
            columns: {
              rssToken: false,
            },
          },
        },
      });

      if (collaborator) {
        list = {
          ...collaborator.list,
          userRole: collaborator.role,
          hasCollaborators: true, // If you're a collaborator, the list has collaborators
        };
        collaboratorEntry = {
          membershipId: collaborator.id,
        };
      }
    }

    if (!list) {
      throw new TRPCError({
        code: "NOT_FOUND",
        message: "List not found",
      });
    }
    if (list.type === "smart") {
      return new SmartList(ctx, list);
    } else {
      return new ManualList(ctx, list, collaboratorEntry);
    }
  }

  private static async getPublicList(
    ctx: Context,
    listId: string,
    token: string | null,
  ) {
    const listdb = await ctx.db.query.bookmarkLists.findFirst({
      where: and(
        eq(bookmarkLists.id, listId),
        or(
          eq(bookmarkLists.public, true),
          token !== null ? eq(bookmarkLists.rssToken, token) : undefined,
        ),
      ),
      with: {
        user: {
          columns: {
            name: true,
          },
        },
      },
    });
    if (!listdb) {
      throw new TRPCError({
        code: "NOT_FOUND",
        message: "List not found",
      });
    }
    return listdb;
  }

  static async getPublicListMetadata(
    ctx: Context,
    listId: string,
    token: string | null,
  ) {
    const listdb = await this.getPublicList(ctx, listId, token);
    return {
      userId: listdb.userId,
      name: listdb.name,
      description: listdb.description,
      icon: listdb.icon,
      ownerName: listdb.user.name,
    };
  }

  static async getPublicListContents(
    ctx: Context,
    listId: string,
    token: string | null,
    pagination: {
      limit: number;
      order: Exclude<ZSortOrder, "relevance">;
      cursor: ZCursor | null | undefined;
    },
  ) {
    const listdb = await this.getPublicList(ctx, listId, token);

    // The token here acts as an authed context, so we can create
    // an impersonating context for the list owner as long as
    // we don't leak the context.
    const authedCtx = await buildImpersonatingAuthedContext(listdb.userId);
    const listObj = List.fromData(
      authedCtx,
      {
        ...listdb,
        userRole: "public",
        hasCollaborators: false, // Public lists don't expose collaborators
      },
      null,
    );
    const bookmarkIds = await listObj.getBookmarkIds();
    const list = listObj.asZBookmarkList();

    const bookmarks = await Bookmark.loadMulti(authedCtx, {
      ids: bookmarkIds,
      includeContent: false,
      limit: pagination.limit,
      sortOrder: pagination.order,
      cursor: pagination.cursor,
    });

    return {
      list: {
        icon: list.icon,
        name: list.name,
        description: list.description,
        ownerName: listdb.user.name,
        numItems: bookmarkIds.length,
      },
      bookmarks: bookmarks.bookmarks.map((b) => b.asPublicBookmark()),
      nextCursor: bookmarks.nextCursor,
    };
  }

  static async create(
    ctx: AuthedContext,
    input: z.infer<typeof zNewBookmarkListSchema>,
  ): Promise<ManualList | SmartList> {
    const [result] = await ctx.db
      .insert(bookmarkLists)
      .values({
        name: input.name,
        description: input.description,
        icon: input.icon,
        userId: ctx.user.id,
        parentId: input.parentId,
        type: input.type,
        query: input.query,
      })
      .returning();
    return this.fromData(
      ctx,
      {
        ...result,
        userRole: "owner",
        hasCollaborators: false, // Newly created lists have no collaborators
      },
      null,
    );
  }

  static async getAll(ctx: AuthedContext) {
    const [ownedLists, sharedLists] = await Promise.all([
      this.getAllOwned(ctx),
      this.getSharedWithUser(ctx),
    ]);
    return [...ownedLists, ...sharedLists];
  }

  static async getAllOwned(
    ctx: AuthedContext,
  ): Promise<(ManualList | SmartList)[]> {
    const lists = await ctx.db.query.bookmarkLists.findMany({
      columns: {
        rssToken: false,
      },
      where: and(eq(bookmarkLists.userId, ctx.user.id)),
      with: {
        collaborators: {
          columns: {
            id: true,
          },
          limit: 1,
        },
      },
    });
    return lists.map((l) =>
      this.fromData(
        ctx,
        {
          ...l,
          userRole: "owner",
          hasCollaborators: l.collaborators.length > 0,
        },
        null /* this is an owned list */,
      ),
    );
  }

  static async forBookmark(ctx: AuthedContext, bookmarkId: string) {
    const lists = await ctx.db.query.bookmarksInLists.findMany({
      where: eq(bookmarksInLists.bookmarkId, bookmarkId),
      with: {
        list: {
          columns: {
            rssToken: false,
          },
          with: {
            collaborators: {
              where: eq(listCollaborators.userId, ctx.user.id),
              columns: {
                id: true,
                role: true,
              },
            },
          },
        },
      },
    });

    // For owner lists, we need to check if they actually have collaborators
    // by querying the collaborators table separately (without user filter)
    const ownerListIds = lists
      .filter((l) => l.list.userId === ctx.user.id)
      .map((l) => l.list.id);

    const listsWithCollaborators = new Set<string>();
    if (ownerListIds.length > 0) {
      // Use a single query with inArray instead of N queries
      const collaborators = await ctx.db.query.listCollaborators.findMany({
        where: inArray(listCollaborators.listId, ownerListIds),
        columns: {
          listId: true,
        },
      });
      collaborators.forEach((c) => {
        listsWithCollaborators.add(c.listId);
      });
    }

    return lists.flatMap((l) => {
      let userRole: "owner" | "editor" | "viewer" | null;
      let collaboratorEntry: ListCollaboratorEntry | null = null;
      if (l.list.collaborators.length > 0) {
        invariant(l.list.collaborators.length == 1);
        userRole = l.list.collaborators[0].role;
        collaboratorEntry = {
          membershipId: l.list.collaborators[0].id,
        };
      } else if (l.list.userId === ctx.user.id) {
        userRole = "owner";
      } else {
        userRole = null;
      }
      return userRole
        ? [
            this.fromData(
              ctx,
              {
                ...l.list,
                userRole,
                hasCollaborators:
                  userRole !== "owner"
                    ? true
                    : listsWithCollaborators.has(l.list.id),
              },
              collaboratorEntry,
            ),
          ]
        : [];
    });
  }

  /**
   * Check if the user can view this list and its bookmarks.
   */
  canUserView(): boolean {
    return switchCase(this.list.userRole, {
      owner: true,
      editor: true,
      viewer: true,
      public: true,
    });
  }

  /**
   * Check if the user can edit this list (add/remove bookmarks).
   */
  canUserEdit(): boolean {
    return switchCase(this.list.userRole, {
      owner: true,
      editor: true,
      viewer: false,
      public: false,
    });
  }

  /**
   * Check if the user can manage this list (edit metadata, delete, manage collaborators).
   * Only the owner can manage the list.
   */
  canUserManage(): boolean {
    return switchCase(this.list.userRole, {
      owner: true,
      editor: false,
      viewer: false,
      public: false,
    });
  }

  /**
   * Ensure the user can view this list. Throws if they cannot.
   */
  ensureCanView(): void {
    if (!this.canUserView()) {
      throw new TRPCError({
        code: "FORBIDDEN",
        message: "User is not allowed to view this list",
      });
    }
  }

  /**
   * Ensure the user can edit this list. Throws if they cannot.
   */
  ensureCanEdit(): void {
    if (!this.canUserEdit()) {
      throw new TRPCError({
        code: "FORBIDDEN",
        message: "User is not allowed to edit this list",
      });
    }
  }

  /**
   * Ensure the user can manage this list. Throws if they cannot.
   */
  ensureCanManage(): void {
    if (!this.canUserManage()) {
      throw new TRPCError({
        code: "FORBIDDEN",
        message: "User is not allowed to manage this list",
      });
    }
  }

  async delete() {
    this.ensureCanManage();
    const res = await this.ctx.db
      .delete(bookmarkLists)
      .where(
        and(
          eq(bookmarkLists.id, this.list.id),
          eq(bookmarkLists.userId, this.ctx.user.id),
        ),
      );
    if (res.changes == 0) {
      throw new TRPCError({ code: "NOT_FOUND" });
    }
  }

  async getChildren(): Promise<(ManualList | SmartList)[]> {
    const lists = await List.getAllOwned(this.ctx);
    const listById = new Map(lists.map((l) => [l.id, l]));

    const adjecencyList = new Map<string, string[]>();

    // Initialize all lists with empty arrays first
    lists.forEach((l) => {
      adjecencyList.set(l.id, []);
    });

    // Then populate the parent-child relationships
    lists.forEach((l) => {
      const parentId = l.asZBookmarkList().parentId;
      if (parentId) {
        const currentChildren = adjecencyList.get(parentId) ?? [];
        currentChildren.push(l.id);
        adjecencyList.set(parentId, currentChildren);
      }
    });

    const resultIds: string[] = [];
    const queue: string[] = [this.list.id];

    while (queue.length > 0) {
      const id = queue.pop()!;
      const children = adjecencyList.get(id) ?? [];
      children.forEach((childId) => {
        queue.push(childId);
        resultIds.push(childId);
      });
    }

    return resultIds.map((id) => listById.get(id)!);
  }

  async update(
    input: z.infer<typeof zEditBookmarkListSchemaWithValidation>,
  ): Promise<void> {
    this.ensureCanManage();
    const result = await this.ctx.db
      .update(bookmarkLists)
      .set({
        name: input.name,
        description: input.description,
        icon: input.icon,
        parentId: input.parentId,
        query: input.query,
        public: input.public,
      })
      .where(
        and(
          eq(bookmarkLists.id, this.list.id),
          eq(bookmarkLists.userId, this.ctx.user.id),
        ),
      )
      .returning();
    if (result.length == 0) {
      throw new TRPCError({ code: "NOT_FOUND" });
    }
    invariant(result[0].userId === this.ctx.user.id);
    // Fetch current collaborators to update hasCollaborators
    const collaboratorsCount =
      await this.ctx.db.query.listCollaborators.findMany({
        where: eq(listCollaborators.listId, this.list.id),
        columns: {
          id: true,
        },
        limit: 1,
      });
    this.list = {
      ...result[0],
      userRole: "owner",
      hasCollaborators: collaboratorsCount.length > 0,
    };
  }

  private async setRssToken(token: string | null) {
    const result = await this.ctx.db
      .update(bookmarkLists)
      .set({ rssToken: token })
      .where(
        and(
          eq(bookmarkLists.id, this.list.id),
          eq(bookmarkLists.userId, this.ctx.user.id),
        ),
      )
      .returning();
    if (result.length == 0) {
      throw new TRPCError({ code: "NOT_FOUND" });
    }
    return result[0].rssToken;
  }

  async getRssToken(): Promise<string | null> {
    this.ensureCanManage();
    const [result] = await this.ctx.db
      .select({ rssToken: bookmarkLists.rssToken })
      .from(bookmarkLists)
      .where(
        and(
          eq(bookmarkLists.id, this.list.id),
          eq(bookmarkLists.userId, this.ctx.user.id),
        ),
      )
      .limit(1);
    return result.rssToken ?? null;
  }

  async regenRssToken() {
    this.ensureCanManage();
    return await this.setRssToken(crypto.randomBytes(32).toString("hex"));
  }

  async clearRssToken() {
    this.ensureCanManage();
    await this.setRssToken(null);
  }

  /**
   * Add a collaborator to this list by email.
   * Creates a pending invitation that must be accepted by the user.
   * Returns the invitation ID.
   */
  async addCollaboratorByEmail(
    email: string,
    role: "viewer" | "editor",
  ): Promise<string> {
    this.ensureCanManage();

    return await ListInvitation.inviteByEmail(this.ctx, {
      email,
      role,
      listId: this.list.id,
      listName: this.list.name,
      listType: this.list.type,
      listOwnerId: this.list.userId,
      inviterUserId: this.ctx.user.id,
      inviterName: this.ctx.user.name ?? null,
    });
  }

  /**
   * Remove a collaborator from this list.
   * Only the list owner can remove collaborators.
   * This also removes all bookmarks that the collaborator added to the list.
   */
  async removeCollaborator(userId: string): Promise<void> {
    this.ensureCanManage();

    const result = await this.ctx.db
      .delete(listCollaborators)
      .where(
        and(
          eq(listCollaborators.listId, this.list.id),
          eq(listCollaborators.userId, userId),
        ),
      );

    if (result.changes === 0) {
      throw new TRPCError({
        code: "NOT_FOUND",
        message: "Collaborator not found",
      });
    }
  }

  /**
   * Allow a user to leave a list (remove themselves as a collaborator).
   * This bypasses the owner check since users should be able to leave lists they're collaborating on.
   * This also removes all bookmarks that the user added to the list.
   */
  async leaveList(): Promise<void> {
    if (this.list.userRole === "owner") {
      throw new TRPCError({
        code: "BAD_REQUEST",
        message:
          "List owners cannot leave their own list. Delete the list instead.",
      });
    }

    const result = await this.ctx.db
      .delete(listCollaborators)
      .where(
        and(
          eq(listCollaborators.listId, this.list.id),
          eq(listCollaborators.userId, this.ctx.user.id),
        ),
      );

    if (result.changes === 0) {
      throw new TRPCError({
        code: "NOT_FOUND",
        message: "Collaborator not found",
      });
    }
  }

  /**
   * Update a collaborator's role.
   */
  async updateCollaboratorRole(
    userId: string,
    role: "viewer" | "editor",
  ): Promise<void> {
    this.ensureCanManage();

    const result = await this.ctx.db
      .update(listCollaborators)
      .set({ role })
      .where(
        and(
          eq(listCollaborators.listId, this.list.id),
          eq(listCollaborators.userId, userId),
        ),
      );

    if (result.changes === 0) {
      throw new TRPCError({
        code: "NOT_FOUND",
        message: "Collaborator not found",
      });
    }
  }

  /**
   * Get all collaborators for this list, including pending invitations.
   * For privacy, pending invitations show masked user info unless the invitation has been accepted.
   */
  async getCollaborators() {
    this.ensureCanView();

    const isOwner = this.list.userId === this.ctx.user.id;

    const [collaborators, invitations] = await Promise.all([
      this.ctx.db.query.listCollaborators.findMany({
        where: eq(listCollaborators.listId, this.list.id),
        with: {
          user: {
            columns: {
              id: true,
              name: true,
              email: true,
            },
          },
        },
      }),
      // Only show invitations for the owner
      isOwner
        ? ListInvitation.invitationsForList(this.ctx, {
            listId: this.list.id,
          })
        : [],
    ]);

    // Get the owner information
    const owner = await this.ctx.db.query.users.findFirst({
      where: eq(users.id, this.list.userId),
      columns: {
        id: true,
        name: true,
        email: true,
      },
    });

    const collaboratorEntries = collaborators.map((c) => {
      return {
        id: c.id,
        userId: c.userId,
        role: c.role,
        status: "accepted" as const,
        addedAt: c.addedAt,
        invitedAt: c.addedAt,
        user: {
          id: c.user.id,
          name: c.user.name,
          // Only show email to the owner for privacy
          email: isOwner ? c.user.email : null,
        },
      };
    });

    return {
      collaborators: [...collaboratorEntries, ...invitations],
      owner: owner
        ? {
            id: owner.id,
            name: owner.name,
            // Only show owner email to the owner for privacy
            email: isOwner ? owner.email : null,
          }
        : null,
    };
  }

  /**
   * Get all lists shared with the user (as a collaborator).
   * Only includes lists where the invitation has been accepted.
   */
  static async getSharedWithUser(
    ctx: AuthedContext,
  ): Promise<(ManualList | SmartList)[]> {
    const collaborations = await ctx.db.query.listCollaborators.findMany({
      where: eq(listCollaborators.userId, ctx.user.id),
      with: {
        list: {
          columns: {
            rssToken: false,
          },
        },
      },
    });

    return collaborations.map((c) =>
      this.fromData(
        ctx,
        {
          ...c.list,
          userRole: c.role,
          hasCollaborators: true, // If you're a collaborator, the list has collaborators
        },
        {
          membershipId: c.id,
        },
      ),
    );
  }

  abstract get type(): "manual" | "smart";
  abstract getBookmarkIds(ctx: AuthedContext): Promise<string[]>;
  abstract getSize(ctx: AuthedContext): Promise<number>;
  abstract addBookmark(bookmarkId: string): Promise<void>;
  abstract removeBookmark(bookmarkId: string): Promise<void>;
  abstract mergeInto(
    targetList: List,
    deleteSourceAfterMerge: boolean,
  ): Promise<void>;
}

export class SmartList extends List {
  parsedQuery: ReturnType<typeof parseSearchQuery> | null = null;

  constructor(ctx: AuthedContext, list: ZBookmarkList & { userId: string }) {
    super(ctx, list);
  }

  get type(): "smart" {
    invariant(this.list.type === "smart");
    return this.list.type;
  }

  get query() {
    invariant(this.list.query);
    return this.list.query;
  }

  getParsedQuery() {
    if (!this.parsedQuery) {
      const result = parseSearchQuery(this.query);
      if (result.result !== "full") {
        throw new Error("Invalid smart list query");
      }
      this.parsedQuery = result;
    }
    return this.parsedQuery;
  }

  async getBookmarkIds(): Promise<string[]> {
    const parsedQuery = this.getParsedQuery();
    if (!parsedQuery.matcher) {
      return [];
    }
    return await getBookmarkIdsFromMatcher(this.ctx, parsedQuery.matcher);
  }

  async getSize(): Promise<number> {
    return await this.getBookmarkIds().then((ids) => ids.length);
  }

  addBookmark(_bookmarkId: string): Promise<void> {
    throw new TRPCError({
      code: "BAD_REQUEST",
      message: "Smart lists cannot be added to",
    });
  }

  removeBookmark(_bookmarkId: string): Promise<void> {
    throw new TRPCError({
      code: "BAD_REQUEST",
      message: "Smart lists cannot be removed from",
    });
  }

  mergeInto(
    _targetList: List,
    _deleteSourceAfterMerge: boolean,
  ): Promise<void> {
    throw new TRPCError({
      code: "BAD_REQUEST",
      message: "Smart lists cannot be merged",
    });
  }
}

export class ManualList extends List {
  constructor(
    ctx: AuthedContext,
    list: ZBookmarkList & { userId: string },
    private collaboratorEntry: ListCollaboratorEntry | null,
  ) {
    super(ctx, list);
  }

  get type(): "manual" {
    invariant(this.list.type === "manual");
    return this.list.type;
  }

  async getBookmarkIds(): Promise<string[]> {
    const results = await this.ctx.db
      .select({ id: bookmarksInLists.bookmarkId })
      .from(bookmarksInLists)
      .where(eq(bookmarksInLists.listId, this.list.id));
    return results.map((r) => r.id);
  }

  async getSize(): Promise<number> {
    const results = await this.ctx.db
      .select({ count: count() })
      .from(bookmarksInLists)
      .where(eq(bookmarksInLists.listId, this.list.id));
    return results[0].count;
  }

  async addBookmark(bookmarkId: string): Promise<void> {
    this.ensureCanEdit();

    try {
      await this.ctx.db.insert(bookmarksInLists).values({
        listId: this.list.id,
        bookmarkId,
        listMembershipId: this.collaboratorEntry?.membershipId,
      });
      await triggerRuleEngineOnEvent(bookmarkId, [
        {
          type: "addedToList",
          listId: this.list.id,
        },
      ]);
    } catch (e) {
      if (e instanceof SqliteError) {
        if (e.code == "SQLITE_CONSTRAINT_PRIMARYKEY") {
          // this is fine, it just means the bookmark is already in the list
          return;
        }
      }
      throw new TRPCError({
        code: "INTERNAL_SERVER_ERROR",
        message: "Something went wrong",
      });
    }
  }

  async removeBookmark(bookmarkId: string): Promise<void> {
    // Check that the user can edit this list
    this.ensureCanEdit();

    const deleted = await this.ctx.db
      .delete(bookmarksInLists)
      .where(
        and(
          eq(bookmarksInLists.listId, this.list.id),
          eq(bookmarksInLists.bookmarkId, bookmarkId),
        ),
      );
    if (deleted.changes == 0) {
      throw new TRPCError({
        code: "BAD_REQUEST",
        message: `Bookmark ${bookmarkId} is already not in list ${this.list.id}`,
      });
    }
    await triggerRuleEngineOnEvent(bookmarkId, [
      {
        type: "removedFromList",
        listId: this.list.id,
      },
    ]);
  }

  async update(input: z.infer<typeof zEditBookmarkListSchemaWithValidation>) {
    if (input.query) {
      throw new TRPCError({
        code: "BAD_REQUEST",
        message: "Manual lists cannot have a query",
      });
    }
    return super.update(input);
  }

  async mergeInto(
    targetList: List,
    deleteSourceAfterMerge: boolean,
  ): Promise<void> {
    this.ensureCanManage();
    targetList.ensureCanManage();
    if (targetList.type !== "manual") {
      throw new TRPCError({
        code: "BAD_REQUEST",
        message: "You can only merge into a manual list",
      });
    }

    const bookmarkIds = await this.getBookmarkIds();

    await this.ctx.db.transaction(async (tx) => {
      await tx
        .insert(bookmarksInLists)
        .values(
          bookmarkIds.map((id) => ({
            bookmarkId: id,
            listId: targetList.id,
          })),
        )
        .onConflictDoNothing();

      if (deleteSourceAfterMerge) {
        await tx
          .delete(bookmarkLists)
          .where(eq(bookmarkLists.id, this.list.id));
      }
    });
  }
}