from django.core.management.base import BaseCommand, CommandError
from apps.accounts.models import User
from apps.business.products.models import Product
from apps.business.distributor.models import DistributorID, distributor_runtime_guard
from apps.business.distributor.services.distributor_service import create_distributor_id as create_runtime_distributor_id

class Command(BaseCommand):
    help = 'Create a distributor or referrer ID for a user and product.'

    def add_arguments(self, parser):
        parser.add_argument('--user', type=int, required=True, help='User ID')
        parser.add_argument('--product', type=int, required=True, help='Product ID')
        parser.add_argument('--referrer', type=int, help='Sponsor distributor ID (optional)')
        parser.add_argument('--code', type=str, help='Distributor code (optional, auto if not provided)')
        parser.add_argument('--active', action='store_true', help='Set as active')

    def handle(self, *args, **options):
        user_id = options['user']
        product_id = options['product']
        sponsor_id = options.get('referrer')
        code = options.get('code')
        is_active = options['active']

        try:
            user = User.objects.get(id=user_id)
            product = Product.objects.get(id=product_id)
            sponsor = None
            if sponsor_id:
                sponsor = DistributorID.objects.get(id=sponsor_id)
        except Exception as e:
            raise CommandError(f'Error: {e}')

        if not code:
            from django.utils.crypto import get_random_string
            code = get_random_string(10).upper()

        dist_id = create_runtime_distributor_id(user, product, sponsor)
        updates = []
        if code and dist_id.distributor_code != code:
            dist_id.distributor_code = code
            updates.append('distributor_code')
        if dist_id.is_active != is_active:
            dist_id.is_active = is_active
            updates.append('is_active')
        if not dist_id.is_auto_generated:
            dist_id.is_auto_generated = True
            updates.append('is_auto_generated')
        if updates:
            with distributor_runtime_guard('management_command:create_distributor_id:post-create'):
                dist_id.save(update_fields=updates)
        self.stdout.write(self.style.SUCCESS(f'DistributorID created: {dist_id.id} code={dist_id.distributor_code} user={user_id} product={product_id} referrer={sponsor_id}'))
