import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  console.log('🌱 Seeding wallets for all existing users...')

  // Create currencies if they don't exist
  console.log('💰 Ensuring currencies exist...')
  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)
    }
  }

  // Get all companies for reference
  const companies = await prisma.company.findMany()
  console.log(`📊 Found ${companies.length} companies`)

  // Create wallets for users in the users table
  console.log('\n👛 Creating wallets for users...')
  const users = await prisma.user.findMany({
    include: { company: true }
  })

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

      if (!existingWallet) {
        const wallet = await prisma.wallet.create({
          data: {
            userType: 'user',
            userId: user.id,
            companyId: user.companyId || user.company?.id || '',
            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)
    }
  }

  // Create wallets for tenants
  console.log('\n🏠 Creating wallets for tenants...')
  const tenants = await prisma.tenant.findMany({
    include: { company: true }
  })

  for (const tenant of tenants) {
    try {
      const existingWallet = await prisma.wallet.findUnique({
        where: {
          userType_tenantId: {
            userType: 'tenant',
            tenantId: tenant.id,
          },
        },
      })

      if (!existingWallet) {
        const wallet = await prisma.wallet.create({
          data: {
            userType: 'tenant',
            tenantId: tenant.id,
            companyId: tenant.companyId,
            currencyId: 'UGX', // Default to UGX
            balance: 0, // Tenants start with 0 balance
          }
        })

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

  // Create wallets for technicians
  console.log('\n🔧 Creating wallets for technicians...')
  const technicians = await prisma.technician.findMany({
    include: { company: true }
  })

  for (const technician of technicians) {
    try {
      const existingWallet = await prisma.wallet.findUnique({
        where: {
          userType_technicianId: {
            userType: 'technician',
            technicianId: technician.id,
          },
        },
      })

      if (!existingWallet) {
        const wallet = await prisma.wallet.create({
          data: {
            userType: 'technician',
            technicianId: technician.id,
            companyId: technician.companyId,
            currencyId: 'UGX', // Default to UGX
            balance: 0, // Technicians start with 0 balance
          }
        })

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

  console.log('\n🎉 Wallet seeding completed!')
  console.log(`📊 Summary:`)
  console.log(`   - Users: ${users.length}`)
  console.log(`   - Tenants: ${tenants.length}`)
  console.log(`   - Technicians: ${technicians.length}`)
  console.log(`   - Total potential wallets: ${users.length + tenants.length + technicians.length}`)
}

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