/**
 * One-off cleanup: merge duplicate conversations that share the same jobId.
 * Run before applying the unique constraint on conversations.jobId.
 */
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function dedupeJobConversations() {
  const duplicateJobIds = await prisma.$queryRaw<{ jobId: string }[]>`
    SELECT jobId FROM conversations
    WHERE jobId IS NOT NULL
    GROUP BY jobId
    HAVING COUNT(*) > 1
  `;

  for (const { jobId } of duplicateJobIds) {
    const conversations = await prisma.conversation.findMany({
      where: { jobId },
      include: { _count: { select: { messages: true } } },
      orderBy: { createdAt: 'asc' },
    });

    const sorted = [...conversations].sort(
      (a, b) =>
        b._count.messages - a._count.messages ||
        a.createdAt.getTime() - b.createdAt.getTime()
    );
    const [keep, ...remove] = sorted;

    for (const duplicate of remove) {
      if (duplicate._count.messages > 0) {
        await prisma.message.updateMany({
          where: { conversationId: duplicate.id },
          data: { conversationId: keep.id },
        });
      }
      await prisma.conversation.delete({ where: { id: duplicate.id } });
      console.log(`Merged conversation ${duplicate.id} into ${keep.id} for job ${jobId}`);
    }
  }

  console.log(`Cleaned ${duplicateJobIds.length} job(s) with duplicate conversations`);
}

dedupeJobConversations()
  .catch((error) => {
    console.error(error);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
