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

const prisma = new PrismaClient()

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

  // 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/john-smith-agreement.pdf'
    },
    {
      firstName: 'Sarah',
      lastName: 'Johnson',
      email: 'sarah.johnson@propmaster.io',
      phone: '+256 700 234 567',
      commissionRate: 10,
      commissionDueDay: 1,
      agreementDocument: '/uploads/agreements/sarah-johnson-agreement.pdf'
    },
    {
      firstName: 'Michael',
      lastName: 'Brown',
      email: 'michael.brown@propmaster.io',
      phone: '+256 700 345 678',
      commissionRate: 15,
      commissionDueDay: 20,
      agreementDocument: '/uploads/agreements/michael-brown-agreement.pdf'
    },
    {
      firstName: 'Emma',
      lastName: 'Davis',
      email: 'emma.davis@propmaster.io',
      phone: '+256 700 456 789',
      commissionRate: 8,
      commissionDueDay: 10,
      agreementDocument: '/uploads/agreements/emma-davis-agreement.pdf'
    }
  ]

  // 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)
    }
  }

  // Create some sample properties for the owners
  const owners = await prisma.user.findMany({
    where: {
      role: 'owner',
      companyId: company.id
    }
  })

  if (owners.length > 0) {
    console.log('\n🏢 Creating sample properties for owners...')

    // Get estates for the company
    const estates = await prisma.estate.findMany({
      where: { companyId: company.id }
    })

    if (estates.length === 0) {
      console.log('⚠️  No estates found. Creating a sample estate first...')

      const sampleEstate = await prisma.estate.create({
        data: {
          companyId: company.id,
          name: 'Sample Estate',
          description: 'A beautiful residential estate',
          location: 'Kampala, Uganda',
          streetAddress: 'Plot 123, Kampala Road',
          city: 'Kampala',
          district: 'Kampala',
          region: 'Central',
          postalCode: '256',
          country: 'Uganda',
          totalProperties: 10,
          totalUnits: 50
        }
      })

      estates.push(sampleEstate)
      console.log(`✅ Created sample estate: ${sampleEstate.name}`)
    }

    // Create properties for owners
    const propertiesData = [
      {
        name: 'Sunset Apartments',
        description: 'Modern apartment complex with ocean views',
        propertyType: 'apartment_building',
        purchasePrice: 500000000, // 500M UGX
        currentMarketValue: 600000000, // 600M UGX
        totalUnits: 20,
        totalFloors: 5,
        yearBuilt: 2020,
        status: 'active'
      },
      {
        name: 'Green Valley Villas',
        description: 'Luxury villas in a serene environment',
        propertyType: 'house',
        purchasePrice: 300000000, // 300M UGX
        currentMarketValue: 350000000, // 350M UGX
        totalUnits: 8,
        totalFloors: 1,
        yearBuilt: 2018,
        status: 'active'
      },
      {
        name: 'City Center Plaza',
        description: 'Commercial property in the heart of the city',
        propertyType: 'commercial',
        purchasePrice: 800000000, // 800M UGX
        currentMarketValue: 900000000, // 900M UGX
        totalUnits: 15,
        totalFloors: 3,
        yearBuilt: 2019,
        status: 'active'
      }
    ]

    for (let i = 0; i < Math.min(owners.length, propertiesData.length); i++) {
      const owner = owners[i]
      const propertyData = propertiesData[i]
      const estate = estates[0] // Use first estate

      try {
        const property = await prisma.property.create({
          data: {
            ...propertyData,
            companyId: company.id,
            estateId: estate.id,
            ownerId: owner.id
          }
        })

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

  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')
}

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