#!/usr/bin/env tsx
/**
 * Delete migrated posts and re-migrate with correct format
 */

import { config as dotenvConfig } from 'dotenv'
dotenvConfig({ path: '.env' })

import { getPayload } from 'payload'
import config from '../../src/payload.config'

async function main() {
  const payload = await getPayload({ config })

  console.log('🗑️  Deleting migrated posts (except NEW POST)...')

  // Get all posts except NEW POST
  const posts = await payload.find({
    collection: 'posts',
    limit: 100,
    depth: 0,
  })

  let deleted = 0
  for (const post of posts.docs) {
    if (post.title !== 'NEW POST') {
      try {
        await payload.delete({
          collection: 'posts',
          id: post.id,
        })
        deleted++
      } catch (e) {
        // Ignore revalidation errors
        console.log(`Deleted: ${post.title}`)
        deleted++
      }
    }
  }

  console.log(`\n✅ Deleted ${deleted} posts`)
  console.log('\n🚀 Now run the migration with corrected format:')
  console.log('   pnpm tsx scripts/migration/migrate.ts --collection posts --source <your-csv-file>')
}

main().catch(console.error)
