# Generated by Django 5.2.8 on 2025-12-10 07:46
"""
Data migration to create Subscription records for existing Tenants.

Maps existing tenant subscription_tier to new billing Subscription model.
"""

from datetime import timedelta

from django.db import migrations
from django.utils import timezone


# Legacy tier to new plan code mapping
TIER_TO_PLAN_CODE = {
    'FREE': 'free',
    'STARTER': 'starter',
    'PROFESSIONAL': 'professional',
    'ENTERPRISE': 'enterprise',
}


def create_subscriptions_for_tenants(apps, schema_editor):
    """Create Subscription records for all existing Tenants."""
    Tenant = apps.get_model('core', 'Tenant')
    Subscription = apps.get_model('billing', 'Subscription')
    Plan = apps.get_model('billing', 'Plan')
    PlanVersion = apps.get_model('billing', 'PlanVersion')

    now = timezone.now()

    for tenant in Tenant.objects.exclude(schema_name='public'):
        # Skip if tenant already has a billing_subscription
        if Subscription.objects.filter(business=tenant).exists():
            continue

        # Map legacy tier to new plan code
        tier = tenant.subscription_tier or 'FREE'
        plan_code = TIER_TO_PLAN_CODE.get(tier, 'free')

        # Get the plan version (latest version of the plan)
        try:
            plan = Plan.objects.get(code=plan_code)
            plan_version = PlanVersion.objects.filter(
                plan=plan,
                is_legacy=False
            ).order_by('-version').first()

            if not plan_version:
                plan_version = PlanVersion.objects.filter(plan=plan).order_by('-version').first()

            if not plan_version:
                # Fallback to free plan
                plan = Plan.objects.get(code='free')
                plan_version = PlanVersion.objects.filter(plan=plan).order_by('-version').first()

        except Plan.DoesNotExist:
            # If plans aren't seeded yet, skip this tenant
            continue

        if not plan_version:
            continue

        # Create subscription
        Subscription.objects.create(
            business=tenant,
            plan_version=plan_version,
            status='active',
            current_period_start=now,
            current_period_end=now + timedelta(days=30),
        )


def reverse_subscriptions(apps, schema_editor):
    """Reverse migration - delete all subscriptions."""
    Subscription = apps.get_model('billing', 'Subscription')
    Subscription.objects.all().delete()


class Migration(migrations.Migration):

    dependencies = [
        ('billing', '0003_seed_initial_plans'),
        ('core', '0001_initial'),  # Ensure core models exist
    ]

    operations = [
        migrations.RunPython(create_subscriptions_for_tenants, reverse_subscriptions),
    ]
