from datetime import timedelta
from django.utils import timezone
# from business.models import Subscription, SubscriptionPackage


# def assign_free_trial_subscription(business):
#     """
#     Assigns a free trial subscription to a business, if allowed.
#     Handles expiration of old trials and avoids duplicates.
#     """
#     try:
#         # Find the first free trial plan
#         plan = SubscriptionPackage.objects.filter(
#             provider='trial',
#             is_free_plan=True,
#             free_trial_days__gt=0
#         ).first()

#         if not plan:
#             return {"success": False, "message": "No free trial plan available."}

#         # Check for existing active trial
#         existing_trial = Subscription.objects.filter(
#             business=business,
#             plan__provider='trial',
#             status='trial'
#         ).order_by('-subscribed_on').first()

#         if existing_trial and existing_trial.current_period_end > timezone.now():
#             return {"success": False, "message": "Active trial already exists."}

#         # Mark existing trial as expired (if any)
#         if existing_trial:
#             existing_trial.status = 'expired'
#             existing_trial.save()

#         # Create new free trial
#         Subscription.objects.create(
#             business=business,
#             plan=plan,
#             status='trial',
#             subscribed_on=timezone.now(),
#             current_period_end=timezone.now() + timedelta(days=plan.free_trial_days)
#         )

#         return {"success": True, "message": f"{plan.free_trial_days}-day free trial assigned."}

#     except Exception as e:
#         return {"success": False, "message": f"Error assigning trial: {str(e)}"}