import type { Prisma, PrismaClient } from "@prisma/client"; import { publishedRuleAnalyticsFromDocument } from "../../lib/create/publishedRuleAnalytics"; import { TEAM_RULE_DRAFT_TITLE, TEAM_RULE_TITLE, buildAdoptedTeamRule, } from "../../lib/create/teamRule"; import { RULE_VISIBILITY } from "../../lib/ruleVisibility"; export type SeedTeamRuleResult = { action: "created" | "updated"; id: string; title: string; }; /** * Replaces the old "The CommunityRule Project" draft with the adopted Rule, * or inserts it when the environment has neither row. */ export async function seedTeamRule( prisma: PrismaClient, ): Promise { const adopted = buildAdoptedTeamRule(); const document = adopted.document as Prisma.InputJsonValue; const analytics = publishedRuleAnalyticsFromDocument(adopted.document); const draftRow = await prisma.publishedRule.findFirst({ where: { title: TEAM_RULE_DRAFT_TITLE }, orderBy: { createdAt: "asc" }, select: { id: true }, }); const adoptedRow = await prisma.publishedRule.findFirst({ where: { title: TEAM_RULE_TITLE }, orderBy: { createdAt: "asc" }, select: { id: true }, }); const existingId = draftRow?.id ?? adoptedRow?.id; const data = { title: adopted.title, summary: adopted.summary, document, visibility: RULE_VISIBILITY.public_and_featured, ...analytics, }; if (existingId) { const row = await prisma.publishedRule.update({ where: { id: existingId }, data, select: { id: true, title: true }, }); return { action: "updated", id: row.id, title: row.title }; } const row = await prisma.publishedRule.create({ data: { userId: null, ...data, }, select: { id: true, title: true }, }); return { action: "created", id: row.id, title: row.title }; }