import random
from django.core.management.base import BaseCommand
from faker import Faker
from kupci.models import Kupac

class Command(BaseCommand):
    help = 'Popunjava bazu podataka s testnim kupcima'

    def add_arguments(self, parser):
        parser.add_argument(
            'total', 
            type=int, 
            help='Broj kupaca koje želiš kreirati',
            default=10
        )

    def handle(self, *args, **kwargs):
        total = kwargs['total']
        fake = Faker(['hr_HR'])
        
        self.stdout.write(self.style.MIGRATE_HEADING(f'🚀 Kreiram {total} kupaca...'))

        created_count = 0
        for _ in range(total):
            tip = random.choice(['pravno', 'fizicko'])
            
            if tip == 'pravno':
                naziv = fake.company()
            else:
                naziv = fake.name()

            # Generiramo OIB (nasumičnih 11 znamenki)
            oib = "".join([str(random.randint(0, 9)) for _ in range(11)])

            try:
                # Koristimo get_or_create ili create da izbjegnemo duplikate OIB-a 
                # ako je polje unique=True u modelu
                Kupac.objects.create(
                    naziv=naziv,
                    oib=oib,
                    email=fake.email(),
                    telefon=fake.phone_number(),
                    adresa=fake.street_address(),
                    grad=fake.city(),
                    postanski_broj=fake.postcode(),
                    tip=tip,
                    napomena="Automatski generiran testni kupac.",
                    aktivno=True
                )
                created_count += 1
            except Exception as e:
                # Ako OIB slučajno bude isti, samo nastavi dalje
                continue

        self.stdout.write(self.style.SUCCESS(f'✅ Uspješno dodano {created_count} novih kupaca!'))