#!/usr/bin/env tsx
/**
 * Fix Post Content Structure
 *
 * Converts migrated posts from direct Lexical format to Payload's {root: ...} 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('🔧 Fixing post content structure...\n')

  const posts = await payload.find({
    collection: 'posts',
    limit: 100,
    depth: 0,
  })

  console.log(`Found ${posts.totalDocs} posts to check\n`)

  let fixed = 0
  let skipped = 0

  for (const post of posts.docs) {
    const id = post.id
    const title = post.title?.substring(0, 40)

    // Check if content is an object (needs fixing)
    if (post.content && typeof post.content === 'object') {
      // Check if it's already in correct format { root: {...} }
      if (post.content.root && typeof post.content.root === 'object') {
        console.log(`⏭️  Skipping (already correct): ${title}`)
        skipped++
        continue
      }

      // Fix: wrap in { root: ... } structure
      const fixedContent = JSON.stringify({ root: post.content })

      try {
        await payload.update({
          collection: 'posts',
          id,
          data: {
            content: fixedContent,
          },
        })
        console.log(`✓ Fixed: ${title}`)
        fixed++
      } catch (error) {
        console.error(`✗ Failed to fix "${title}":`, error)
      }
    } else if (post.content && typeof post.content === 'string') {
      // String content - check if it needs fixing
      try {
        const parsed = JSON.parse(post.content)
        if (parsed.root) {
          console.log(`⏭️  Skipping (already correct): ${title}`)
          skipped++
        } else {
          // Need to wrap in { root: ... }
          const fixedContent = JSON.stringify({ root: parsed })
          await payload.update({
            collection: 'posts',
            id,
            data: { content: fixedContent },
          })
          console.log(`✓ Fixed: ${title}`)
          fixed++
        }
      } catch (e) {
        console.log(`⏭️  Skipping (invalid JSON): ${title}`)
        skipped++
      }
    } else {
      skipped++
    }
  }

  console.log(`\n✅ Fixed ${fixed} posts`)
  console.log(`⏭️ Skipped ${skipped} posts`)
}

main().catch(console.error)
