import { prisma } from "@/lib/db";

export async function deleteTopicWithRelations(topicId: string) {
  const topic = await prisma.topic.findUnique({ where: { id: topicId } });
  if (!topic) throw new Error("找不到主題");

  const drafts = await prisma.draft.findMany({
    where: { topicId },
    select: { id: true },
  });

  if (drafts.length > 0) {
    await prisma.draft.deleteMany({ where: { topicId } });
  }

  await prisma.published.deleteMany({ where: { topicId } });

  await prisma.scan.deleteMany({ where: { topicId } });
  await prisma.topic.delete({ where: { id: topicId } });

  return {
    deletedDrafts: drafts.length,
  };
}