import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  console.log('🌱 Seeding wallet data...')

  // Create currencies
  console.log('💰 Creating currencies...')
  const currencies = [
    { code: 'UGX', name: 'Ugandan Shilling', symbol: 'UGX' },
    { code: 'USD', name: 'US Dollar', symbol: '$' },
    { code: 'EUR', name: 'Euro', symbol: '€' },
    { code: 'GBP', name: 'British Pound', symbol: '£' },
  ]

  for (const currency of currencies) {
    try {
      const existing = await prisma.currency.findUnique({
        where: { code: currency.code }
      })

      if (!existing) {
        await prisma.currency.create({
          data: {
            ...currency,
            isActive: true
          }
        })
        console.log(`✅ Created currency: ${currency.name} (${currency.code})`)
      } else {
        console.log(`⚠️  Currency ${currency.code} already exists, skipping...`)
      }
    } catch (error) {
      console.error(`❌ Error creating currency ${currency.code}:`, error)
    }
  }

  // Create exchange rates
  console.log('\n💱 Creating exchange rates...')
  const ugxCurrency = await prisma.currency.findUnique({ where: { code: 'UGX' } })
  const usdCurrency = await prisma.currency.findUnique({ where: { code: 'USD' } })
  const eurCurrency = await prisma.currency.findUnique({ where: { code: 'EUR' } })
  const gbpCurrency = await prisma.currency.findUnique({ where: { code: 'GBP' } })

  if (ugxCurrency && usdCurrency && eurCurrency && gbpCurrency) {
    const exchangeRates = [
      { fromId: usdCurrency.id, toId: ugxCurrency.id, rate: 3700, fromCode: 'USD' },
      { fromId: eurCurrency.id, toId: ugxCurrency.id, rate: 4000, fromCode: 'EUR' },
      { fromId: gbpCurrency.id, toId: ugxCurrency.id, rate: 4700, fromCode: 'GBP' },
    ]

    for (const rate of exchangeRates) {
      try {
        await prisma.exchangeRate.create({
          data: {
            fromCurrencyId: rate.fromId,
            toCurrencyId: rate.toId,
            rate: rate.rate,
            source: 'manual',
            effectiveDate: new Date()
          }
        })
        console.log(`✅ Created exchange rate: 1 ${rate.fromCode} = ${rate.rate} UGX`)
      } catch (error) {
        console.error(`❌ Error creating exchange rate for ${rate.fromCode}:`, error)
      }
    }
  }

  // Get all users and create wallets for them
  console.log('\n👛 Creating wallets for existing users...')
  const users = await prisma.user.findMany({
    include: { company: true }
  })

  for (const user of users) {
    try {
      const existingWallet = await prisma.wallet.findFirst({
        where: {
          userType: 'user',
          userId: user.id
        }
      })

      if (!existingWallet && user.companyId) {
        const wallet = await prisma.wallet.create({
          data: {
            userType: 'user',
            userId: user.id,
            companyId: user.companyId,
            currencyId: 'UGX', // Default to UGX
            balance: user.role === 'company_admin' ? 100000 : user.role === 'owner' ? 50000 : 0, // Sample balances
          }
        })

        // Create sample transactions for some users
        if (user.role === 'company_admin' || user.role === 'owner') {
          await prisma.walletTransaction.create({
            data: {
              walletId: wallet.id,
              companyId: wallet.companyId,
              transactionType: 'top_up',
              amount: wallet.balance,
              currency: 'UGX',
              description: 'Initial wallet setup',
              paymentMethod: 'cash',
              status: 'completed',
            }
          })
        }

        console.log(`✅ Created wallet for ${user.firstName} ${user.lastName} (${user.role}) with balance: ${wallet.balance} UGX`)
      } else {
        console.log(`⚠️  Wallet for ${user.email} already exists, skipping...`)
      }
    } catch (error) {
      console.error(`❌ Error creating wallet for ${user.email}:`, error)
    }
  }

  console.log('\n🎉 Wallet seeding completed!')
  console.log(`📊 Created ${currencies.length} currencies`)
  console.log(`👛 Created wallets for ${users.length} users`)
}

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