import mongoose from 'mongoose'
import Event from '../server/models/event.js'
import { connectDB } from '../server/utils/mongoose.js'

// Generate slug from title
function generateSlug(title) {
  return title
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
}

async function migrateEventSlugs() {
  try {
    // Connect to database
    await connectDB()
    console.log('Connected to database')

    // Find all events without slugs
    const eventsWithoutSlugs = await Event.find({
      $or: [
        { slug: { $exists: false } },
        { slug: null },
        { slug: '' }
      ]
    })

    console.log(`Found ${eventsWithoutSlugs.length} events without slugs`)

    if (eventsWithoutSlugs.length === 0) {
      console.log('All events already have slugs!')
      return
    }

    // Generate and assign unique slugs
    for (const event of eventsWithoutSlugs) {
      let baseSlug = generateSlug(event.title)
      let slug = baseSlug
      let counter = 1

      // Ensure slug is unique
      while (await Event.findOne({ slug, _id: { $ne: event._id } })) {
        slug = `${baseSlug}-${counter}`
        counter++
      }

      event.slug = slug
      await event.save({ validateBeforeSave: false }) // Skip validation to avoid pre-save hook
      console.log(`✓ Generated slug "${slug}" for event "${event.title}"`)
    }

    console.log(`Successfully migrated ${eventsWithoutSlugs.length} events!`)
  } catch (error) {
    console.error('Error migrating event slugs:', error)
  } finally {
    await mongoose.connection.close()
    console.log('Database connection closed')
  }
}

// Run migration if called directly
if (import.meta.url === `file://${process.argv[1]}`) {
  migrateEventSlugs()
}

export default migrateEventSlugs