import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// Book key mapping for consistent cross-version identification
const bookKeyMapping: Record<string, string> = {
  'Geneza': 'genesis',
  'Genesis': 'genesis',
  'Exodul': 'exodus',
  'Exodus': 'exodus',
  'Leviticul': 'leviticus',
  'Leviticus': 'leviticus',
  'Numerii': 'numbers',
  'Numbers': 'numbers',
  // Add more as needed
}

function getBookKey(bookName: string): string {
  return bookKeyMapping[bookName] || bookName.toLowerCase().replace(/\s+/g, '_')
}

async function migrateToVersionedSchema() {
  console.log('Starting migration to versioned Bible schema...')

  try {
    // Step 1: Create Bible versions
    console.log('Creating Bible versions...')

    const romanianVersion = await prisma.bibleVersion.upsert({
      where: { abbreviation_language: { abbreviation: 'CORNILESCU', language: 'ro' } },
      update: {},
      create: {
        name: 'Cornilescu',
        abbreviation: 'CORNILESCU',
        language: 'ro',
        description: 'Biblia Cornilescu în limba română',
        isDefault: true
      }
    })

    const englishVersion = await prisma.bibleVersion.upsert({
      where: { abbreviation_language: { abbreviation: 'BSB', language: 'en' } },
      update: {},
      create: {
        name: 'Berean Standard Bible',
        abbreviation: 'BSB',
        language: 'en',
        description: 'English Bible - Berean Standard Bible',
        isDefault: true
      }
    })

    console.log(`Created versions: ${romanianVersion.id} (RO), ${englishVersion.id} (EN)`)

    // Step 2: Get all existing books and migrate them
    console.log('Migrating existing books...')

    // Note: This assumes your current BibleBook table has the old structure
    // We'll need to query the old structure and create new versioned books

    const existingBooks = await prisma.$queryRaw<any[]>`
      SELECT id, name, testament, "orderNum" FROM "BibleBook" ORDER BY "orderNum"
    `

    for (const oldBook of existingBooks) {
      const bookKey = getBookKey(oldBook.name)

      // Create Romanian version of the book (assuming current data is Romanian)
      const roBook = await prisma.bibleBook.create({
        data: {
          versionId: romanianVersion.id,
          name: oldBook.name,
          testament: oldBook.testament,
          orderNum: oldBook.orderNum,
          bookKey: bookKey
        }
      })

      console.log(`Created Romanian book: ${roBook.name} (${bookKey})`)

      // Get all chapters for this book and migrate them
      const existingChapters = await prisma.$queryRaw<any[]>`
        SELECT id, "chapterNum" FROM "BibleChapter" WHERE "bookId" = ${oldBook.id} ORDER BY "chapterNum"
      `

      for (const oldChapter of existingChapters) {
        const newChapter = await prisma.bibleChapter.create({
          data: {
            bookId: roBook.id,
            chapterNum: oldChapter.chapterNum
          }
        })

        // Get all verses for this chapter and migrate them (Romanian only)
        const existingVerses = await prisma.$queryRaw<any[]>`
          SELECT id, "verseNum", text FROM "BibleVerse"
          WHERE "chapterId" = ${oldChapter.id} AND version = 'KJV'
          ORDER BY "verseNum"
        `

        for (const oldVerse of existingVerses) {
          await prisma.bibleVerse.create({
            data: {
              chapterId: newChapter.id,
              verseNum: oldVerse.verseNum,
              text: oldVerse.text
            }
          })
        }

        console.log(`  Migrated chapter ${oldChapter.chapterNum} with ${existingVerses.length} verses`)
      }

      // Also create English version if we have English data
      const englishVerses = await prisma.$queryRaw<any[]>`
        SELECT COUNT(*) as count FROM "BibleVerse" v
        JOIN "BibleChapter" c ON v."chapterId" = c.id
        WHERE c."bookId" = ${oldBook.id} AND v.version = 'EN'
      `

      if (englishVerses[0]?.count > 0) {
        // Map English book name (you might need to improve this mapping)
        const englishBookName = oldBook.name === 'Geneza' ? 'Genesis' :
                                oldBook.name === 'Exodul' ? 'Exodus' :
                                oldBook.name

        const enBook = await prisma.bibleBook.create({
          data: {
            versionId: englishVersion.id,
            name: englishBookName,
            testament: oldBook.testament,
            orderNum: oldBook.orderNum,
            bookKey: bookKey
          }
        })

        // Migrate English chapters and verses
        for (const oldChapter of existingChapters) {
          const enChapter = await prisma.bibleChapter.create({
            data: {
              bookId: enBook.id,
              chapterNum: oldChapter.chapterNum
            }
          })

          const englishVerses = await prisma.$queryRaw<any[]>`
            SELECT "verseNum", text FROM "BibleVerse"
            WHERE "chapterId" = ${oldChapter.id} AND version = 'EN'
            ORDER BY "verseNum"
          `

          for (const enVerse of englishVerses) {
            await prisma.bibleVerse.create({
              data: {
                chapterId: enChapter.id,
                verseNum: enVerse.verseNum,
                text: enVerse.text
              }
            })
          }
        }

        console.log(`Created English book: ${englishBookName}`)
      }
    }

    console.log('Migration completed successfully!')
    console.log(`Romanian version ID: ${romanianVersion.id}`)
    console.log(`English version ID: ${englishVersion.id}`)

  } catch (error) {
    console.error('Migration failed:', error)
    throw error
  }
}

// Run the migration
migrateToVersionedSchema()
  .then(() => {
    console.log('Migration completed successfully!')
    process.exit(0)
  })
  .catch((error) => {
    console.error('Migration failed:', error)
    process.exit(1)
  })
  .finally(() => prisma.$disconnect())