#!/usr/bin/env tsx
import { config as dotenvConfig } from 'dotenv'
import { resolve, dirname } from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
// Script is at: apps/backend/scripts/migration/test-create-post.ts
// .env is at: apps/backend/.env
const envPath = resolve(__dirname, '../../.env')

dotenvConfig({ path: envPath })

// Verify env is loaded
console.log('PAYLOAD_SECRET loaded:', !!process.env.PAYLOAD_SECRET)
console.log('PAYLOAD_SECRET value:', process.env.PAYLOAD_SECRET?.substring(0, 10))

// Dynamic import after dotenv to ensure env is loaded before config
const { getPayload } = await import('payload')
const config = await import('../../src/payload.config.ts')
const { parseWebflowCSV } = await import('./csvParser.ts')
const { transformPosts } = await import('./transformers.ts')

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

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

  console.log('Attempting to create:', transformed.title)
  console.log('Slug:', transformed.slug)

  try {
    const result = await payload.create({
      collection: 'posts',
      data: transformed,
    })
    console.log('Success! Created:', result.id)
  } catch (error: any) {
    console.log('Failed!')
    console.log('Error message:', error.message)
    if (error.data) {
      console.log('Error data:', JSON.stringify(error.data, null, 2))
    }
  }
}

main().catch(console.error)
