#!/usr/bin/env tsx
/**
 * Test Payload Post Creation - Two Step Approach
 */

import { getPayload } from 'payload'
import config from '@payload-config'

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

  const testSlug = 'test-two-step-' + Date.now()
  let postId = ''

  // Step 1: Create post without content
  console.log('\n🧪 Step 1: Create post without content')
  try {
    const result = await payload.create({
      collection: 'posts',
      data: {
        title: 'Test Two Step Post',
        slug: testSlug,
        publishedAt: new Date(),
        status: 'draft',
        // No content field
      },
    })
    console.log('✓ Post created without content:', result.id)
    postId = result.id
  } catch (error: any) {
    console.log('✗ Failed:', error.message)
    if (error.data) {
      console.error('  Errors:', JSON.stringify(error.data, null, 2))
    }
    return
  }

  // Step 2: Update with content
  console.log('\n🧪 Step 2: Update post with content (object)')
  try {
    const updated = await payload.update({
      collection: 'posts',
      id: postId,
      data: {
        content: {
          type: 'root',
          version: 1,
          children: [{
            type: 'paragraph',
            version: 1,
            children: [{
              type: 'text',
              version: 1,
              text: 'This is a test paragraph.'
            }]
          }],
          direction: null
        },
      },
    })
    console.log('✓ Post updated with object content:', updated.id)
  } catch (error: any) {
    console.log('✗ Object content failed:', error.message)
  }

  // Step 3: Try JSON string content
  console.log('\n🧪 Step 3: Update with JSON string content')
  try {
    const updated = await payload.update({
      collection: 'posts',
      id: postId,
      data: {
        content: JSON.stringify({
          type: 'root',
          version: 1,
          children: [{
            type: 'paragraph',
            version: 1,
            children: [{
              type: 'text',
              version: 1,
              text: 'This is a test paragraph from JSON string.'
            }]
          }],
          direction: null
        }),
      },
    })
    console.log('✓ Post updated with JSON string content:', updated.id)
  } catch (error: any) {
    console.log('✗ JSON string content failed:', error.message)
  }

  // Cleanup
  console.log('\n🧪 Cleanup: Delete test post')
  try {
    await payload.delete({
      collection: 'posts',
      id: postId,
    })
    console.log('✓ Test post deleted')
  } catch (error: any) {
    console.log('✗ Delete failed:', error.message)
  }
}

testTwoStepPost().catch(console.error)
