# Generated by Django 5.2.8 on 2025-12-10 07:45
"""
Data migration to seed initial billing Features, Plans, and PlanVersions.

Maps from legacy tiers (FREE, STARTER, PROFESSIONAL, ENTERPRISE) to new billing models.
"""

from django.db import migrations


def seed_features(apps, schema_editor):
    """Create initial Feature records."""
    Feature = apps.get_model('billing', 'Feature')

    features = [
        # Boolean features (permissions)
        {'code': 'can_accept_payments', 'name': 'Accept Payments', 'feature_type': 'boolean',
         'description': 'Accept online payments via Stripe Connect'},
        {'code': 'can_use_custom_domain', 'name': 'Custom Domain', 'feature_type': 'boolean',
         'description': 'Configure a custom domain for your booking page'},
        {'code': 'can_white_label', 'name': 'White Labeling', 'feature_type': 'boolean',
         'description': 'Remove SmoothSchedule branding'},
        {'code': 'can_api_access', 'name': 'API Access', 'feature_type': 'boolean',
         'description': 'Access the API for integrations'},
        {'code': 'can_use_sms_reminders', 'name': 'SMS Reminders', 'feature_type': 'boolean',
         'description': 'Send SMS reminders to customers and staff'},
        {'code': 'can_use_masked_phone_numbers', 'name': 'Masked Phone Numbers', 'feature_type': 'boolean',
         'description': 'Use masked phone numbers for privacy'},
        {'code': 'can_use_mobile_app', 'name': 'Mobile App', 'feature_type': 'boolean',
         'description': 'Access the mobile app for field employees'},
        {'code': 'can_use_contracts', 'name': 'Contracts', 'feature_type': 'boolean',
         'description': 'Create and manage e-signature contracts'},
        {'code': 'can_use_calendar_sync', 'name': 'Calendar Sync', 'feature_type': 'boolean',
         'description': 'Sync with Google Calendar and other providers'},
        {'code': 'can_use_webhooks', 'name': 'Webhooks', 'feature_type': 'boolean',
         'description': 'Use webhooks for integrations'},
        {'code': 'can_use_plugins', 'name': 'Plugins', 'feature_type': 'boolean',
         'description': 'Use plugins from the marketplace'},
        {'code': 'can_use_tasks', 'name': 'Scheduled Tasks', 'feature_type': 'boolean',
         'description': 'Create scheduled tasks (requires plugins)'},
        {'code': 'can_export_data', 'name': 'Data Export', 'feature_type': 'boolean',
         'description': 'Export data (appointments, customers, etc.)'},
        {'code': 'can_add_video_conferencing', 'name': 'Video Conferencing', 'feature_type': 'boolean',
         'description': 'Add video conferencing to events'},
        {'code': 'can_book_repeated_events', 'name': 'Recurring Events', 'feature_type': 'boolean',
         'description': 'Book recurring/repeated events'},
        {'code': 'can_require_2fa', 'name': 'Require 2FA', 'feature_type': 'boolean',
         'description': 'Require two-factor authentication for users'},
        {'code': 'can_download_logs', 'name': 'Download Logs', 'feature_type': 'boolean',
         'description': 'Download system logs'},
        {'code': 'can_delete_data', 'name': 'Delete Data', 'feature_type': 'boolean',
         'description': 'Permanently delete data'},
        {'code': 'can_use_pos', 'name': 'Point of Sale', 'feature_type': 'boolean',
         'description': 'Use Point of Sale (POS) system'},
        {'code': 'can_manage_oauth_credentials', 'name': 'Manage OAuth', 'feature_type': 'boolean',
         'description': 'Manage your own OAuth credentials'},
        {'code': 'can_connect_to_api', 'name': 'Connect to API', 'feature_type': 'boolean',
         'description': 'Connect to external APIs'},
        {'code': 'can_create_plugins', 'name': 'Create Plugins', 'feature_type': 'boolean',
         'description': 'Create custom plugins for automation'},

        # Integer features (limits)
        {'code': 'max_users', 'name': 'Max Users', 'feature_type': 'integer',
         'description': 'Maximum number of users'},
        {'code': 'max_resources', 'name': 'Max Resources', 'feature_type': 'integer',
         'description': 'Maximum number of resources'},
        {'code': 'max_event_types', 'name': 'Max Event Types', 'feature_type': 'integer',
         'description': 'Maximum number of event types'},
        {'code': 'max_calendars_connected', 'name': 'Max Calendars', 'feature_type': 'integer',
         'description': 'Maximum number of external calendars connected'},
    ]

    for feature_data in features:
        Feature.objects.get_or_create(
            code=feature_data['code'],
            defaults={
                'name': feature_data['name'],
                'feature_type': feature_data['feature_type'],
                'description': feature_data.get('description', ''),
            }
        )


def seed_plans_and_versions(apps, schema_editor):
    """Create initial Plan and PlanVersion records."""
    Plan = apps.get_model('billing', 'Plan')
    PlanVersion = apps.get_model('billing', 'PlanVersion')
    Feature = apps.get_model('billing', 'Feature')
    PlanFeature = apps.get_model('billing', 'PlanFeature')

    # Get features for reference
    def get_feature(code):
        try:
            return Feature.objects.get(code=code)
        except Feature.DoesNotExist:
            return None

    # Plan definitions matching legacy tiers
    plans_data = [
        {
            'code': 'free',
            'name': 'Free',
            'description': 'Get started with basic scheduling',
            'display_order': 1,
            'versions': [
                {
                    'version': 1,
                    'name': 'Free Plan',
                    'price_monthly_cents': 0,
                    'price_yearly_cents': 0,
                    'is_public': True,
                    'features': {
                        # Boolean features
                        'can_book_repeated_events': True,
                        'can_use_plugins': True,
                        # Integer limits
                        'max_users': 2,
                        'max_resources': 3,
                        'max_event_types': 3,
                    }
                }
            ]
        },
        {
            'code': 'starter',
            'name': 'Starter',
            'description': 'Perfect for small businesses',
            'display_order': 2,
            'versions': [
                {
                    'version': 1,
                    'name': 'Starter Plan',
                    'price_monthly_cents': 2900,  # $29/month
                    'price_yearly_cents': 29000,  # $290/year
                    'is_public': True,
                    'features': {
                        # Boolean features
                        'can_accept_payments': True,
                        'can_book_repeated_events': True,
                        'can_use_plugins': True,
                        'can_use_tasks': True,
                        'can_export_data': True,
                        'can_use_calendar_sync': True,
                        # Integer limits
                        'max_users': 5,
                        'max_resources': 10,
                        'max_event_types': 10,
                        'max_calendars_connected': 3,
                    }
                }
            ]
        },
        {
            'code': 'professional',
            'name': 'Professional',
            'description': 'For growing teams that need more power',
            'display_order': 3,
            'versions': [
                {
                    'version': 1,
                    'name': 'Professional Plan',
                    'price_monthly_cents': 7900,  # $79/month
                    'price_yearly_cents': 79000,  # $790/year
                    'is_public': True,
                    'features': {
                        # Boolean features
                        'can_accept_payments': True,
                        'can_use_custom_domain': True,
                        'can_book_repeated_events': True,
                        'can_use_plugins': True,
                        'can_use_tasks': True,
                        'can_export_data': True,
                        'can_use_calendar_sync': True,
                        'can_use_sms_reminders': True,
                        'can_use_mobile_app': True,
                        'can_use_contracts': True,
                        'can_add_video_conferencing': True,
                        'can_api_access': True,
                        # Integer limits
                        'max_users': 15,
                        'max_resources': 30,
                        'max_event_types': 25,
                        'max_calendars_connected': 10,
                    }
                }
            ]
        },
        {
            'code': 'enterprise',
            'name': 'Enterprise',
            'description': 'Full-featured solution for large organizations',
            'display_order': 4,
            'versions': [
                {
                    'version': 1,
                    'name': 'Enterprise Plan',
                    'price_monthly_cents': 19900,  # $199/month
                    'price_yearly_cents': 199000,  # $1990/year
                    'is_public': True,
                    'features': {
                        # Boolean features - all enabled
                        'can_accept_payments': True,
                        'can_use_custom_domain': True,
                        'can_white_label': True,
                        'can_api_access': True,
                        'can_use_sms_reminders': True,
                        'can_use_masked_phone_numbers': True,
                        'can_use_mobile_app': True,
                        'can_use_contracts': True,
                        'can_use_calendar_sync': True,
                        'can_use_webhooks': True,
                        'can_use_plugins': True,
                        'can_use_tasks': True,
                        'can_create_plugins': True,
                        'can_export_data': True,
                        'can_add_video_conferencing': True,
                        'can_book_repeated_events': True,
                        'can_require_2fa': True,
                        'can_download_logs': True,
                        'can_delete_data': True,
                        'can_use_pos': True,
                        'can_manage_oauth_credentials': True,
                        'can_connect_to_api': True,
                        # Integer limits - generous
                        'max_users': 50,
                        'max_resources': 100,
                        'max_event_types': 100,
                        'max_calendars_connected': 50,
                    }
                }
            ]
        },
    ]

    for plan_data in plans_data:
        plan, _ = Plan.objects.get_or_create(
            code=plan_data['code'],
            defaults={
                'name': plan_data['name'],
                'description': plan_data['description'],
                'display_order': plan_data['display_order'],
            }
        )

        for version_data in plan_data['versions']:
            pv, created = PlanVersion.objects.get_or_create(
                plan=plan,
                version=version_data['version'],
                defaults={
                    'name': version_data['name'],
                    'price_monthly_cents': version_data['price_monthly_cents'],
                    'price_yearly_cents': version_data['price_yearly_cents'],
                    'is_public': version_data.get('is_public', True),
                    'is_legacy': version_data.get('is_legacy', False),
                }
            )

            # Create PlanFeature records if the PlanVersion was just created
            if created:
                for feature_code, value in version_data['features'].items():
                    feature = get_feature(feature_code)
                    if feature:
                        if feature.feature_type == 'boolean':
                            PlanFeature.objects.get_or_create(
                                plan_version=pv,
                                feature=feature,
                                defaults={'bool_value': value}
                            )
                        elif feature.feature_type == 'integer':
                            PlanFeature.objects.get_or_create(
                                plan_version=pv,
                                feature=feature,
                                defaults={'int_value': value}
                            )


def reverse_seed(apps, schema_editor):
    """Reverse migration - delete seeded data."""
    Feature = apps.get_model('billing', 'Feature')
    Plan = apps.get_model('billing', 'Plan')

    # Delete in reverse order of dependencies
    Plan.objects.filter(code__in=['free', 'starter', 'professional', 'enterprise']).delete()
    Feature.objects.all().delete()


class Migration(migrations.Migration):

    dependencies = [
        ('billing', '0002_add_invoice_models'),
    ]

    operations = [
        # Only seed features - plans should be created via Platform Settings UI
        migrations.RunPython(seed_features, reverse_seed),
        # NOTE: seed_plans_and_versions removed - plans are created via UI
        # migrations.RunPython(seed_plans_and_versions, migrations.RunPython.noop),
    ]
