/**
 * Idempotent sync: ensure every project with a submittedByUserId has a
 * corresponding TeamMember(LEAD) record. Safe to run on every deploy.
 */

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  const projects = await prisma.project.findMany({
    where: { submittedByUserId: { not: null } },
    select: {
      id: true,
      submittedByUserId: true,
      teamMembers: { select: { userId: true } },
    },
  })

  const toCreate: Array<{ projectId: string; userId: string; role: 'LEAD' }> = []

  for (const project of projects) {
    if (!project.submittedByUserId) continue
    const alreadyLinked = project.teamMembers.some(
      (tm) => tm.userId === project.submittedByUserId
    )
    if (!alreadyLinked) {
      toCreate.push({
        projectId: project.id,
        userId: project.submittedByUserId,
        role: 'LEAD',
      })
    }
  }

  if (toCreate.length > 0) {
    await prisma.teamMember.createMany({
      data: toCreate,
      skipDuplicates: true,
    })
    console.log(`✓ Linked ${toCreate.length} project submitters as TeamMember(LEAD)`)
  } else {
    console.log('✓ All project submitters already linked — nothing to do')
  }
}

main()
  .catch((e) => {
    console.error('Team lead sync failed:', e)
    process.exit(1)
  })
  .finally(() => prisma.$disconnect())
