import { type ListEvents, listEvents } from '@/lib/events' import type { Database } from '@/lib/prisma' /** * Grants membership for every `pending`, non-expired invitation that matches the * email and marks those invitations as accepted. * * Called right after a BetterAuth user is created, so people who are invited * before signing up see the shared lists as soon as they register. * * @returns how many invitations were accepted */ export async function acceptPendingInvitations( db: Database, { userId, email }: { userId: string; email: string }, events: ListEvents = listEvents, ): Promise { const pending = await db.shoppingListInvitation.findMany({ where: { email, status: 'pending', expiresAt: { gt: new Date() } }, }) for (const invitation of pending) { await db.$transaction([ db.shoppingListMember.upsert({ where: { listId_userId: { listId: invitation.listId, userId } }, update: {}, create: { listId: invitation.listId, userId, role: 'collaborator' }, }), db.shoppingListInvitation.update({ where: { id: invitation.id }, data: { status: 'accepted', acceptedAt: new Date() }, }), ]) events.publish({ type: 'member.added', listId: invitation.listId, userId }) } return pending.length } /** * Guarantees the user has at least one list: when they belong to none, creates a * "Lista principal" owned by them and marks it as their primary list. Called * right after a BetterAuth user is created (after pending invitations are * accepted) so every account has a starting point. */ export async function ensurePrimaryList( db: Database, { userId }: { userId: string }, ): Promise { const memberships = await db.shoppingListMember.count({ where: { userId } }) if (memberships > 0) return await db.shoppingList.create({ data: { name: 'Lista principal', ownerId: userId, members: { create: { userId, role: 'owner', isPrimary: true } }, }, }) }