#!/usr/bin/env tsx
/**
 * Fix Post Content Format
 *
 * Converts post content from object to JSON string format
 * for Payload CMS richText field compatibility
 */

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 format...')

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

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

  let fixed = 0
  let skipped = 0

  for (const post of posts.docs) {
    // Check if content is an object (needs fixing)
    if (post.content && typeof post.content === 'object') {
      const id = post.id
      const title = post.title?.substring(0, 40) + '...'

      // Convert to JSON string
      const contentJson = JSON.stringify(post.content)

      try {
        await payload.update({
          collection: 'posts',
          id,
          data: {
            content: contentJson,
          },
        })
        console.log(`✓ Fixed: ${title}`)
        fixed++
      } catch (error) {
        console.error(`✗ Failed to fix ${title}:`, error)
      }
    } else {
      skipped++
    }
  }

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

main().catch(console.error)
