import { eq, notInArray } from 'drizzle-orm'
import { useDB, schema } from '../db'
import { scanMusicFolder } from '../utils/fileScanner'
import { generateBlurhash } from '../utils/blurHash'

const { cards } = schema

export async function syncCardsWithDatabase(folderPath: string) {
  const db = useDB()
  const scannedCards = await scanMusicFolder(folderPath)

  console.log(`📁 ${scannedCards.length} cards trouvées dans le dossier`)

  // 1. Récupérer les cards existantes en DB
  const existingCards = await db.select().from(cards).all()
  const existingEsids = new Set(existingCards.map((t) => t.esid))

  // 2. Identifier les nouvelles cards à ajouter
  const cardsToInsert = scannedCards.filter((card) => !existingEsids.has(card.esid))

  // 3. Identifier les cards à supprimer
  const scannedEsids = new Set(scannedCards.map((t) => t.esid))
  const cardsToDelete = existingCards.filter((t) => !scannedEsids.has(t.esid))

  // 4. Insérer les nouvelles cartes
  if (cardsToInsert.length > 0) {
    // Générer tous les blurhash en parallèle
    const cardsWithBlurhash = await Promise.all(
      cardsToInsert.map(async (card) => {
        const blurhash = await generateBlurhash(card.url_image)
        return {
          url_audio: card.url_audio,
          url_image: card.url_image,
          year: card.year,
          month: card.month,
          day: card.day,
          hour: card.hour,
          artist: card.artist,
          title: card.title,
          esid: card.esid,
          slug: card.slug,
          createdAt: card.createdAt,
          suit: card.suit,
          rank: card.rank,
          blurhash: blurhash
        }
      })
    )

    // Insérer les cartes avec les blurhash déjà résolus
    await db.insert(cards).values(cardsWithBlurhash)
    console.log(`✅ ${cardsToInsert.length} cartes ajoutées`)
  }

  // 5. Supprimer les cards obsolètes avec une requête distincte pour chaque esid
  for (const cardToDelete of cardsToDelete) {
    await db.delete(cards).where(eq(cards.esid, cardToDelete.esid))
    console.log(`🗑️  ${cardsToDelete.length} cards supprimées`)
  }

  return {
    added: cardsToInsert.length,
    deleted: cardsToDelete.length,
    total: scannedCards.length
  }
}
