#!/usr/bin/env tsx
/**
 * Test MongoDB and Payload CMS Connection
 */

import { config as dotenvConfig } from 'dotenv'
import { resolve, dirname } from 'path'
import { fileURLToPath } from 'url'

// Resolve .env path from script location
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const envPath = resolve(__dirname, '../../../.env')

console.log(`Loading .env from: ${envPath}`)
dotenvConfig({ path: envPath })

import { getPayload } from 'payload'
import config from '../../src/payload.config'

async function testMongoDirect() {
  console.log('\n🔍 Testing Environment Variables...\n')

  const uri = process.env.DATABASE_URI
  console.log(`DATABASE_URI: ${uri?.replace(/:[^:@]+@/, ':****@')}`)

  if (!uri) {
    console.log('❌ DATABASE_URI not set')
    return false
  }

  console.log('✅ DATABASE_URI is set')
  return true
}

async function testPayloadAPI() {
  console.log('\n🔍 Testing Payload CMS API Connection...\n')

  try {
    const payload = await getPayload({ config })
    console.log('✅ Payload CMS initialized')

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

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

    if (posts.docs.length > 0) {
      const post = posts.docs[0]
      console.log(`\n📋 First post:`)
      console.log(`   Title: ${post.title}`)
      console.log(`   Slug: ${post.slug}`)
      console.log(`   Content Type: ${typeof post.content}`)

      if (typeof post.content === 'string') {
        try {
          const parsed = JSON.parse(post.content)
          console.log(`   Lexical Type: ${parsed?.type}`)
          console.log(`   Lexical Version: ${parsed?.version}`)
          console.log(`   Children Count: ${parsed?.children?.length}`)
        } catch {
          console.log(`   Content (first 200 chars): ${post.content.substring(0, 200)}...`)
        }
      }
    }

    return true
  } catch (error) {
    console.log('❌ Payload CMS connection failed:', error)
    return false
  }
}

async function main() {
  console.log('═══════════════════════════════════════════════════════════')
  console.log('Connection Test')
  console.log('═══════════════════════════════════════════════════════════')

  const mongoOk = await testMongoDirect()
  const payloadOk = await testPayloadAPI()

  console.log('\n═══════════════════════════════════════════════════════════')
  console.log('Summary:')
  console.log(`  DATABASE_URI: ${mongoOk ? '✅ OK' : '❌ FAILED'}`)
  console.log(`  Payload CMS: ${payloadOk ? '✅ OK' : '❌ FAILED'}`)
  console.log('═══════════════════════════════════════════════════════════\n')
}

main().catch(console.error)
