import { createClient } from '@sanity/client'
import dotenv from 'dotenv'

dotenv.config()

const client = createClient({
  projectId: process.env.SANITY_PROJECT_ID,
  dataset: process.env.SANITY_DATASET || 'production',
  apiVersion: '2024-01-01',
  useCdn: false,
  token: process.env.SANITY_API_TOKEN,
})

async function cleanDuplicates() {
  console.log('🔍 Recherche des produits...\n')

  const products = await client.fetch(
    `*[_type == "product"] | order(name asc, _createdAt asc) { _id, name, slug, _createdAt }`
  )

  console.log(`  Total: ${products.length} produits trouvés\n`)

  // Group by slug
  const grouped = {}
  for (const p of products) {
    const key = p.slug?.current || p.name
    if (!grouped[key]) grouped[key] = []
    grouped[key].push(p)
  }

  const toDelete = []
  for (const [key, docs] of Object.entries(grouped)) {
    if (docs.length > 1) {
      console.log(`  ⚠️  "${key}" — ${docs.length} exemplaires`)
      // Keep the first (oldest), delete the rest
      const [keep, ...duplicates] = docs
      console.log(`     ✓ Garder: ${keep._id} (${keep._createdAt})`)
      for (const dup of duplicates) {
        console.log(`     ✗ Supprimer: ${dup._id} (${dup._createdAt})`)
        toDelete.push(dup._id)
      }
      console.log()
    }
  }

  if (toDelete.length === 0) {
    console.log('✅ Aucun doublon trouvé !')
    return
  }

  console.log(`\n🗑️  Suppression de ${toDelete.length} doublon(s)...\n`)

  const tx = client.transaction()
  for (const id of toDelete) {
    tx.delete(id)
  }
  await tx.commit()

  console.log('✅ Doublons supprimés !')
}

cleanDuplicates().catch((err) => {
  console.error('❌ Erreur:', err.message)
  process.exit(1)
})
