import random
from faker import Faker
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from core.models import Customer, Lead, Opportunity, ContactHistory, Tenant

User = get_user_model()

class Command(BaseCommand):
    help = 'Seeds the database with sample customers, leads, opportunities, and contact histories.'

    def handle(self, *args, **options):
        self.stdout.write("Starting database seeding...")

        faker = Faker()

        # Clean up existing data
        Tenant.objects.all().delete()
        User.objects.filter(is_superuser=False).delete()
        Customer.objects.all().delete()
        Lead.objects.all().delete()
        Opportunity.objects.all().delete()
        ContactHistory.objects.all().delete()

        self.stdout.write("Cleared existing data.")

        # Create sample tenants
        tenants = []
        for _ in range(3):
            tenant = Tenant.objects.create(name=faker.company())
            tenants.append(tenant)
        self.stdout.write(f"Created {len(tenants)} sample tenants.")

        # Create sample users
        users = []
        for _ in range(5):
            email = faker.email()
            # Avoid creating a user that might already exist
            if not User.objects.filter(email=email).exists():
                user = User.objects.create_user(email=email, password='password123')
                users.append(user)
        
        if not users:
            # If all generated users already existed, create one with a predictable email
            user = User.objects.create_user(email='testuser@example.com', password='password123')
            users.append(user)


        self.stdout.write(f"Created {len(users)} sample users.")

        # Create sample customers
        customers = []
        for _ in range(150):
            customer = Customer.objects.create(
                name=faker.company(),
                email=faker.unique.email(),
                phone=faker.phone_number(),
                status=random.choice(['Active', 'Inactive', 'Prospective']),
                tenant=random.choice(tenants),
                created_by=random.choice(users),
                updated_by=random.choice(users),
            )
            customers.append(customer)

        self.stdout.write(f"Created {len(customers)} sample customers.")

        # Create related objects
        for customer in customers:
            # Create contact history
            for _ in range(random.randint(0, 5)):
                ContactHistory.objects.create(
                    customer=customer,
                    user=random.choice(users),
                    note=faker.sentence(),
                    interaction_type=random.choice(['Call', 'Email', 'Meeting']),
                )

            # Create leads
            leads = []
            for _ in range(random.randint(0, 3)):
                lead = Lead.objects.create(
                    customer=customer,
                    source=random.choice(['Web', 'Referral', 'Partner']),
                    status=random.choice(['New', 'Contacted', 'Qualified']),
                    assigned_to=random.choice(users),
                )
                leads.append(lead)
            
            # Create opportunities
            if leads:
                for _ in range(random.randint(0, 2)):
                    Opportunity.objects.create(
                        lead=random.choice(leads),
                        value=faker.pydecimal(left_digits=5, right_digits=2, positive=True),
                        stage=random.choice(['Prospecting', 'Proposal', 'Negotiation', 'Closed Won', 'Closed Lost']),
                        probability=random.uniform(0.1, 0.9),
                        close_date=faker.future_date(),
                    )


        self.stdout.write("Seeding complete.")
