import { and, eq, isNull, ne } from 'drizzle-orm'; import { contentTargetInProject } from './access.ts'; import { db, tables } from './db/index.ts'; import { contentTargetFromColumns, type ContentTarget } from '#lib/content-target.ts'; export type LivePlotCard = typeof tables.plotCard.$inferSelect & { column: ContentTarget; }; export function liveCardInProject(projectId: string, cardId: string): LivePlotCard | null { const row = db .select({ card: tables.plotCard }) .from(tables.plotCard) .innerJoin(tables.storyline, eq(tables.storyline.id, tables.plotCard.storylineId)) .innerJoin(tables.project, eq(tables.project.id, tables.storyline.projectId)) .where( and( eq(tables.plotCard.id, cardId), eq(tables.storyline.projectId, projectId), isNull(tables.plotCard.deletedAt), isNull(tables.storyline.deletedAt), isNull(tables.project.deletedAt) ) ) .get()?.card; if (!row) return null; const column = contentTargetFromColumns(row); if (!column || !contentTargetInProject(projectId, column)) return null; return { ...row, column }; } export function liveCardInCell(storylineId: string, column: ContentTarget, exceptId?: string) { return db .select({ id: tables.plotCard.id }) .from(tables.plotCard) .where( and( isNull(tables.plotCard.deletedAt), eq(tables.plotCard.storylineId, storylineId), column.kind === 'scene' ? eq(tables.plotCard.sceneId, column.id) : eq(tables.plotCard.chapterId, column.id), exceptId ? ne(tables.plotCard.id, exceptId) : undefined ) ) .get(); }