import { PrismaClient } from '@prisma/client'
import bcrypt from 'bcrypt'

const prisma = new PrismaClient()

async function main() {
  console.log('Starting database seeding...')

  // Create English language
  const english = await prisma.language.upsert({
    where: { code: 'en' },
    update: {},
    create: {
      code: 'en',
      name: 'English',
      nativeName: 'English',
      isActive: true,
    },
  })

  console.log('Created language:', english.name)

  // Create admin user
  const hashedPassword = await bcrypt.hash('admin123', 10)
  const adminUser = await prisma.user.upsert({
    where: { email: 'admin@memohanzi.local' },
    update: {},
    create: {
      email: 'admin@memohanzi.local',
      password: hashedPassword,
      name: 'Admin User',
      role: 'ADMIN',
      isActive: true,
      preference: {
        create: {
          preferredLanguageId: english.id,
          characterDisplay: 'SIMPLIFIED',
          transcriptionType: 'pinyin',
          cardsPerSession: 20,
          dailyGoal: 50,
          removalThreshold: 10,
          allowManualDifficulty: true,
        },
      },
    },
  })

  console.log('Created admin user:', adminUser.email)

  // Create test user
  const testPassword = await bcrypt.hash('test123', 10)
  const testUser = await prisma.user.upsert({
    where: { email: 'user@memohanzi.local' },
    update: {},
    create: {
      email: 'user@memohanzi.local',
      password: testPassword,
      name: 'Test User',
      role: 'USER',
      isActive: true,
      preference: {
        create: {
          preferredLanguageId: english.id,
          characterDisplay: 'SIMPLIFIED',
          transcriptionType: 'pinyin',
          cardsPerSession: 20,
          dailyGoal: 50,
          removalThreshold: 10,
          allowManualDifficulty: true,
        },
      },
    },
  })

  console.log('Created test user:', testUser.email)

  console.log('Database seeding completed!')
}

main()
  .catch((e) => {
    console.error('Error during seeding:', e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })
