import random
import string
from django.db.models.signals import post_migrate
from django.dispatch import receiver
from django.utils import timezone
from datetime import timedelta

@receiver(post_migrate)
def create_initial_data(sender, **kwargs):
    if sender.name != 'core':
        return

    from core.models import SystemSettings, SubscriptionPlan, License

    # Create default Subscription Plan if none exists
    plan, created_plan = SubscriptionPlan.objects.get_or_create(
        code='UNLIMITED_LIFETIME',
        defaults={
            'name': 'Unlimited Lifetime Plan',
            'max_products': 0,
            'max_categories': 0,
            'max_orders_per_day': 0,
            'max_users': 0,
            'allow_barcode_scanner': True,
            'allow_credit_sales': True,
            'max_customers': 0,
            'allow_dynamic_fields': True,
            'allow_multi_branch': True,
            'allow_advanced_reports': True,
            'allow_grid_pos': True,
            'allow_pnl_report': True,
            'allow_audit_log': True,
        }
    )

    # Create default SystemSettings if none exists
    settings_qs = SystemSettings.objects.all()
    if not settings_qs.exists():
        # Generate a 30 character random string
        chars = string.ascii_uppercase + string.digits
        random_code = ''.join(random.choices(chars, k=30))
        
        system = SystemSettings.objects.create(
            business_name='Modern POS Business',
            is_activated=False,
            activation_code=random_code
        )
    else:
        system = settings_qs.first()
        # Ensure it has an activation code if it was added newly to an existing db
        if not system.activation_code:
            chars = string.ascii_uppercase + string.digits
            system.activation_code = ''.join(random.choices(chars, k=30))
            system.save()

    # Create default License if none exists
    if not License.objects.filter(system=system).exists():
        License.objects.create(
            system=system,
            plan=plan,
            license_key='DEF-LIC-KEY-999',
            is_active=True,
            started_at=timezone.now().date(),
            expires_at=timezone.now().date() + timedelta(days=3650) # 10 years
        )
