const { PrismaClient } = require('@prisma/client')
const bcrypt = require('bcryptjs')

const prisma = new PrismaClient()

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

  try {
    // Get the first company to associate owners with
    const company = await prisma.company.findFirst()
    if (!company) {
      console.log('❌ No company found. Please create a company first.')
      return
    }

    console.log(`📍 Using company: ${company.name} (${company.id})`)

    // Sample owners data
    const ownersData = [
      {
        firstName: 'John',
        lastName: 'Smith',
        email: 'john.smith@propmaster.io',
        phone: '+256 700 123 456',
        commissionRate: 12,
        commissionDueDay: 15,
        agreementDocument: '/uploads/agreements/sample-john-smith-agreement.txt'
      },
      {
        firstName: 'Sarah',
        lastName: 'Johnson',
        email: 'sarah.johnson@propmaster.io',
        phone: '+256 700 234 567',
        commissionRate: 10,
        commissionDueDay: 1,
        agreementDocument: '/uploads/agreements/sample-sarah-johnson-agreement.txt'
      }
    ]

    // Create owners
    for (const ownerData of ownersData) {
      try {
        const existingUser = await prisma.user.findUnique({
          where: { email: ownerData.email }
        })

        if (existingUser) {
          console.log(`⚠️  Owner ${ownerData.email} already exists, skipping...`)
          continue
        }

        const hashedPassword = await bcrypt.hash('password123', 12)

        const owner = await prisma.user.create({
          data: {
            ...ownerData,
            passwordHash: hashedPassword,
            role: 'owner',
            companyId: company.id,
            emailVerified: true,
            timezone: 'Africa/Kampala'
          }
        })

        console.log(`✅ Created owner: ${owner.firstName} ${owner.lastName} (${owner.email})`)
      } catch (error) {
        console.error(`❌ Error creating owner ${ownerData.email}:`, error.message)
      }
    }

    console.log('\n🎉 Owner seeding completed!')
    console.log(`📊 Created ${ownersData.length} sample owners`)
    console.log('🔐 Default password for all owners: password123')
    console.log('📧 You can now log in with any owner email')

  } catch (error) {
    console.error('❌ Error seeding owners:', error.message)
  } finally {
    await prisma.$disconnect()
  }
}

main()