import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from '@superlist/shared' import type { Database } from '@/lib/prisma' import { summaryCountInclude, toSummary } from '../serialize' /** Creates a shopping list owned by the user. The first list becomes primary. */ export class CreateShoppingList { constructor(private readonly db: Database) {} async execute(input: { name: string userId: string }): Promise> { const existingCount = await this.db.shoppingListMember.count({ where: { userId: input.userId }, }) const list = await this.db.shoppingList.create({ data: { name: input.name, ownerId: input.userId, members: { create: { userId: input.userId, role: 'owner', isPrimary: existingCount === 0, }, }, }, include: { ...summaryCountInclude, members: { where: { userId: input.userId } }, }, }) const membership = list.members[0] if (!membership) { throw new Error('Membership was not created for the new list') } return Ok( toSummary({ role: membership.role, isPrimary: membership.isPrimary, isPinned: membership.isPinned, icon: membership.icon, list: { id: list.id, name: list.name, createdAt: list.createdAt, updatedAt: list.updatedAt, _count: list._count, }, }), ) } }