#!/usr/bin/env tsx
import { config as dotenvConfig } from 'dotenv'
dotenvConfig({ path: '.env' })

import { getPayload } from 'payload'
import config from '../../src/payload.config'
import { parseWebflowCSV } from './csvParser'
import { transformPosts } from './transformers'

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

  const data = await parseWebflowCSV('/Users/pukpuk/Dev/website-enchun-mgr/恩群數位行銷 - 行銷放大鏡集.csv')
  const post = data.posts.find((p: any) => p.title.includes('一點都不難'))

  if (!post) {
    console.log('Post not found')
    return
  }

  const transformed = transformPosts([post])[0]

  console.log('Title:', transformed.title)
  console.log('Content type:', typeof transformed.content)

  // Try create without content first
  try {
    const result = await payload.create({
      collection: 'posts',
      data: {
        title: transformed.title,
        slug: transformed.slug + '-test',
        status: 'draft',
      },
    })
    console.log('Created without content:', result.id)

    // Now update with content
    await payload.update({
      collection: 'posts',
      id: result.id,
      data: { content: transformed.content },
    })
    console.log('Updated with content successfully!')

    // Verify
    const updated = await payload.findByID({ collection: 'posts', id: result.id, depth: 0 })
    console.log('Verified content type:', typeof updated.content)
  } catch (error: any) {
    console.log('Error:', error.message)
  }
}

main().catch(console.error)
