// Import directly from the generated client
const { PrismaClient } = require('./node_modules/@prisma/client')
const prisma = new PrismaClient()

async function checkLabels() {
  try {
    console.log('\n=== TOUS LES LABELS DANS LA TABLE Label ===')
    const allLabels = await prisma.label.findMany({
      select: { id: true, name: true, userId: true }
    })
    console.log(`Total: ${allLabels.length} labels`)
    allLabels.forEach(l => {
      console.log(`  - ${l.name} (userId: ${l.userId}, id: ${l.id})`)
    })

    console.log('\n=== TOUS LES LABELS DANS LES NOTES (Note.labels) ===')
    const allNotes = await prisma.note.findMany({
      select: { id: true, labels: true, userId: true }
    })

    const labelsInNotes = new Set()
    allNotes.forEach(note => {
      if (note.labels) {
        try {
          const parsed = Array.isArray(note.labels) ? note.labels : []
          if (Array.isArray(parsed)) {
            parsed.forEach(l => labelsInNotes.add(l))
          }
        } catch (e) {}
      }
    })

    console.log(`Total unique: ${labelsInNotes.size} labels`)
    labelsInNotes.forEach(l => console.log(`  - ${l}`))

    console.log('\n=== LABELS ORPHELINS (dans Label table MAIS PAS dans les notes) ===')
    const orphanLabels = []
    allLabels.forEach(label => {
      let found = false
      labelsInNotes.forEach(noteLabel => {
        if (noteLabel.toLowerCase() === label.name.toLowerCase()) {
          found = true
        }
      })
      if (!found) {
        orphanLabels.push(label)
      }
    })

    console.log(`Total orphans: ${orphanLabels.length}`)
    orphanLabels.forEach(l => {
      console.log(`  - ${l.name} (userId: ${l.userId})`)
    })

    console.log('\n=== LABELS MANQUANTS (dans notes MAIS PAS dans Label table) ===')
    const missingLabels = []
    const existingLabelNames = new Set()
    allLabels.forEach(l => existingLabelNames.add(l.name.toLowerCase()))

    labelsInNotes.forEach(noteLabel => {
      if (!existingLabelNames.has(noteLabel.toLowerCase())) {
        missingLabels.push(noteLabel)
      }
    })

    console.log(`Total missing: ${missingLabels.length}`)
    missingLabels.forEach(l => console.log(`  - ${l}`))

  } catch (error) {
    console.error('Error:', error)
  } finally {
    await prisma.$disconnect()
  }
}

checkLabels()
