"""
Management command to seed the billing catalog with Plans, Features, and AddOns.

Usage:
    python manage.py billing_seed_catalog

This command is idempotent - safe to run multiple times.
It will create or update all records without duplicating data.
"""

from django.core.management.base import BaseCommand
from django.db import transaction

from smoothschedule.billing.models import (
    Feature,
    Plan,
    PlanVersion,
    PlanFeature,
    AddOnProduct,
    AddOnFeature,
)


# =============================================================================
# Feature Catalog (authoritative)
#
# This is the SINGLE SOURCE OF TRUTH for all features.
# The frontend dynamically loads features from this catalog via the API.
#
# Fields:
#   - code: Unique identifier (used in PlanFeature, AddOnFeature)
#   - name: Display name in UI
#   - description: Tooltip/help text
#   - feature_type: "boolean" or "integer"
#   - category: UI grouping (limits, payments, communication, etc.)
#   - tenant_field_name: Corresponding field on Tenant model for overrides
#   - display_order: Order within category (lower = first)
#   - depends_on: Code of parent feature (optional)
# =============================================================================

FEATURES = [
    # --- Limits (integer) ---
    {"code": "max_users", "name": "Maximum Users", "description": "Maximum number of team member accounts", "feature_type": "integer", "category": "limits", "tenant_field_name": "max_users", "display_order": 10},
    {"code": "max_resources", "name": "Maximum Resources", "description": "Maximum number of resources (staff, rooms, equipment)", "feature_type": "integer", "category": "limits", "tenant_field_name": "max_resources", "display_order": 20},
    {"code": "max_locations", "name": "Maximum Locations", "description": "Maximum number of business locations", "feature_type": "integer", "category": "limits", "tenant_field_name": "max_locations", "display_order": 30},
    {"code": "max_services", "name": "Maximum Services", "description": "Maximum number of service types", "feature_type": "integer", "category": "limits", "tenant_field_name": "max_services", "display_order": 40},
    {"code": "max_customers", "name": "Maximum Customers", "description": "Maximum number of customer records", "feature_type": "integer", "category": "limits", "tenant_field_name": "max_customers", "display_order": 50},
    {"code": "max_appointments_per_month", "name": "Monthly Appointments", "description": "Maximum appointments per month", "feature_type": "integer", "category": "limits", "tenant_field_name": "max_appointments_per_month", "display_order": 60},
    {"code": "max_sms_per_month", "name": "Monthly SMS", "description": "Maximum SMS messages per month", "feature_type": "integer", "category": "limits", "tenant_field_name": "max_sms_per_month", "display_order": 70},
    {"code": "max_email_per_month", "name": "Monthly Emails", "description": "Maximum emails per month", "feature_type": "integer", "category": "limits", "tenant_field_name": "max_email_per_month", "display_order": 80},
    {"code": "max_storage_mb", "name": "Storage (MB)", "description": "File storage limit in megabytes", "feature_type": "integer", "category": "limits", "tenant_field_name": "max_storage_mb", "display_order": 90},
    {"code": "max_api_calls_per_day", "name": "Daily API Calls", "description": "Maximum API calls per day", "feature_type": "integer", "category": "limits", "tenant_field_name": "max_api_calls_per_day", "display_order": 100},

    # --- Payments & Revenue ---
    {"code": "payment_processing", "name": "Online Payments", "description": "Accept online payments from customers", "feature_type": "boolean", "category": "payments", "tenant_field_name": "can_accept_payments", "display_order": 10},
    {"code": "can_process_refunds", "name": "Process Refunds", "description": "Issue refunds for payments", "feature_type": "boolean", "category": "payments", "tenant_field_name": "can_process_refunds", "display_order": 20},
    {"code": "can_create_packages", "name": "Service Packages", "description": "Create and sell service packages", "feature_type": "boolean", "category": "payments", "tenant_field_name": "can_create_packages", "display_order": 30},
    {"code": "can_use_pos", "name": "POS System", "description": "Point of sale for in-person payments", "feature_type": "boolean", "category": "payments", "tenant_field_name": "can_use_pos", "display_order": 40},

    # --- Communication ---
    {"code": "email_enabled", "name": "Email Notifications", "description": "Send email notifications and reminders", "feature_type": "boolean", "category": "communication", "tenant_field_name": "email_enabled", "display_order": 10},
    {"code": "sms_enabled", "name": "SMS Messaging", "description": "Send SMS notifications and reminders", "feature_type": "boolean", "category": "communication", "tenant_field_name": "can_use_sms_reminders", "display_order": 20},
    {"code": "masked_calling_enabled", "name": "Masked Calling", "description": "Make calls with masked caller ID for privacy", "feature_type": "boolean", "category": "communication", "tenant_field_name": "can_use_masked_phone_numbers", "display_order": 30},
    {"code": "can_use_email_templates", "name": "Email Templates", "description": "Custom email templates for communications", "feature_type": "boolean", "category": "communication", "tenant_field_name": "can_use_email_templates", "display_order": 40},

    # --- Customization ---
    {"code": "online_booking", "name": "Online Booking", "description": "Allow customers to book appointments online", "feature_type": "boolean", "category": "customization", "tenant_field_name": "online_booking", "display_order": 10},
    {"code": "custom_branding", "name": "Custom Branding", "description": "Customize branding colors, logo, and styling", "feature_type": "boolean", "category": "customization", "tenant_field_name": "can_customize_booking_page", "display_order": 20},
    {"code": "custom_domain", "name": "Custom Domain", "description": "Use your own domain for booking pages", "feature_type": "boolean", "category": "customization", "tenant_field_name": "can_use_custom_domain", "display_order": 30},
    {"code": "remove_branding", "name": "Remove Branding", "description": "Remove SmoothSchedule branding from customer-facing pages", "feature_type": "boolean", "category": "customization", "tenant_field_name": "can_white_label", "display_order": 40},
    {"code": "white_label", "name": "White Label", "description": "Remove all SmoothSchedule branding completely", "feature_type": "boolean", "category": "customization", "tenant_field_name": "can_white_label", "display_order": 50},
    {"code": "max_public_pages", "name": "Public Web Pages", "description": "Maximum number of public-facing web pages", "feature_type": "integer", "category": "customization", "tenant_field_name": "max_public_pages", "display_order": 55},

    # --- Automations ---
    {"code": "can_use_automations", "name": "Use Automations", "description": "Install and use marketplace automations", "feature_type": "boolean", "category": "automations", "tenant_field_name": "can_use_automations", "display_order": 10},
    {"code": "can_use_tasks", "name": "Scheduled Tasks", "description": "Create automated scheduled tasks", "feature_type": "boolean", "category": "automations", "tenant_field_name": "can_use_tasks", "display_order": 20, "depends_on": "can_use_automations"},
    {"code": "can_create_automations", "name": "Create Automations", "description": "Build custom automations", "feature_type": "boolean", "category": "automations", "tenant_field_name": "can_create_automations", "display_order": 30, "depends_on": "can_use_automations"},

    # --- Advanced Features ---
    {"code": "api_access", "name": "API Access", "description": "Access the public API for integrations", "feature_type": "boolean", "category": "advanced", "tenant_field_name": "can_api_access", "display_order": 10},
    {"code": "integrations_enabled", "name": "Integrations", "description": "Connect with third-party services and apps", "feature_type": "boolean", "category": "advanced", "tenant_field_name": "can_use_webhooks", "display_order": 20},
    {"code": "can_use_calendar_sync", "name": "Calendar Sync", "description": "Sync with Google Calendar, etc.", "feature_type": "boolean", "category": "advanced", "tenant_field_name": "can_use_calendar_sync", "display_order": 30},
    {"code": "can_export_data", "name": "Data Export", "description": "Export data to CSV/Excel", "feature_type": "boolean", "category": "advanced", "tenant_field_name": "can_export_data", "display_order": 40},
    {"code": "can_add_video_conferencing", "name": "Video Conferencing", "description": "Add video links to appointments", "feature_type": "boolean", "category": "advanced", "tenant_field_name": "can_add_video_conferencing", "display_order": 50},
    {"code": "advanced_reporting", "name": "Advanced Analytics", "description": "Detailed reporting and analytics", "feature_type": "boolean", "category": "advanced", "tenant_field_name": "advanced_reporting", "display_order": 60},
    {"code": "can_use_contracts", "name": "Contracts", "description": "Create and manage e-signature contracts", "feature_type": "boolean", "category": "advanced", "tenant_field_name": "can_use_contracts", "display_order": 70},
    {"code": "mobile_app_access", "name": "Mobile App", "description": "Access the mobile app for on-the-go management", "feature_type": "boolean", "category": "advanced", "tenant_field_name": "can_use_mobile_app", "display_order": 80},
    {"code": "audit_logs", "name": "Audit Logs", "description": "Track all changes with detailed audit logs", "feature_type": "boolean", "category": "advanced", "tenant_field_name": "can_download_logs", "display_order": 90},
    {"code": "multi_location", "name": "Multi-Location", "description": "Manage multiple business locations", "feature_type": "boolean", "category": "advanced", "tenant_field_name": "multi_location", "display_order": 100},

    # --- Scheduling ---
    {"code": "recurring_appointments", "name": "Recurring Appointments", "description": "Schedule recurring appointments", "feature_type": "boolean", "category": "scheduling", "tenant_field_name": "can_book_repeated_events", "display_order": 10},

    # --- Enterprise & Security ---
    {"code": "can_manage_oauth", "name": "Manage OAuth", "description": "Configure custom OAuth credentials", "feature_type": "boolean", "category": "enterprise", "tenant_field_name": "can_manage_oauth_credentials", "display_order": 10},
    {"code": "team_permissions", "name": "Team Permissions", "description": "Advanced role-based permissions for team members", "feature_type": "boolean", "category": "enterprise", "tenant_field_name": "can_require_2fa", "display_order": 20},
    {"code": "sla_guarantee", "name": "SSO / SAML", "description": "Single sign-on integration", "feature_type": "boolean", "category": "enterprise", "tenant_field_name": "sso_enabled", "display_order": 30},
    {"code": "priority_support", "name": "Priority Support", "description": "Get priority customer support response", "feature_type": "boolean", "category": "enterprise", "tenant_field_name": "priority_support", "display_order": 40},
    {"code": "dedicated_account_manager", "name": "Dedicated Support", "description": "Get a dedicated account manager", "feature_type": "boolean", "category": "enterprise", "tenant_field_name": "dedicated_support", "display_order": 50},
]


# =============================================================================
# Plan Definitions
# =============================================================================

PLANS = [
    {
        "code": "free",
        "name": "Free",
        "description": "Perfect for individuals just getting started",
        "display_order": 1,
        "version": {
            "name": "Free Plan",
            "price_monthly_cents": 0,
            "price_yearly_cents": 0,
            "is_public": True,
            "is_most_popular": False,
            "show_price": True,
            "trial_days": 0,
        },
        "boolean_features": {
            "email_enabled": True,
            "online_booking": True,
            "recurring_appointments": True,
        },
        "integer_features": {
            "max_users": 1,
            "max_resources": 1,
            "max_locations": 1,
            "max_services": 5,
            "max_customers": 200,
            "max_appointments_per_month": 100,
            "max_email_per_month": 300,
            "max_storage_mb": 250,
            "max_api_calls_per_day": 0,
            "max_sms_per_month": 0,
            "max_public_pages": 0,
        },
    },
    {
        "code": "starter",
        "name": "Starter",
        "description": "Great for small businesses getting organized",
        "display_order": 2,
        "version": {
            "name": "Starter Plan",
            "price_monthly_cents": 1900,
            "price_yearly_cents": 19000,
            "is_public": True,
            "is_most_popular": False,
            "show_price": True,
            "trial_days": 14,
        },
        "boolean_features": {
            "email_enabled": True,
            "online_booking": True,
            "recurring_appointments": True,
            "payment_processing": True,
            "mobile_app_access": True,
            "can_use_email_templates": True,
            "can_use_automations": True,
            "can_process_refunds": True,
        },
        "integer_features": {
            "max_users": 3,
            "max_resources": 3,
            "max_locations": 1,
            "max_services": 20,
            "max_customers": 2000,
            "max_appointments_per_month": 500,
            "max_email_per_month": 3000,
            "max_storage_mb": 2000,
            "max_api_calls_per_day": 0,
            "max_sms_per_month": 0,
            "max_public_pages": 1,
        },
    },
    {
        "code": "growth",
        "name": "Growth",
        "description": "For growing teams that need more power",
        "display_order": 3,
        "version": {
            "name": "Growth Plan",
            "price_monthly_cents": 5900,
            "price_yearly_cents": 59000,
            "is_public": True,
            "is_most_popular": True,
            "show_price": True,
            "trial_days": 14,
        },
        "boolean_features": {
            "email_enabled": True,
            "online_booking": True,
            "recurring_appointments": True,
            "payment_processing": True,
            "mobile_app_access": True,
            "sms_enabled": True,
            "custom_domain": True,
            "integrations_enabled": True,
            "can_use_email_templates": True,
            "can_use_automations": True,
            "can_use_tasks": True,
            "can_process_refunds": True,
            "can_use_calendar_sync": True,
            "can_export_data": True,
            "can_add_video_conferencing": True,
            "can_create_packages": True,
        },
        "integer_features": {
            "max_users": 10,
            "max_resources": 10,
            "max_locations": 3,
            "max_services": 75,
            "max_customers": 10000,
            "max_appointments_per_month": 2000,
            "max_email_per_month": 10000,
            "max_sms_per_month": 2000,
            "max_storage_mb": 10000,
            "max_api_calls_per_day": 10000,
            "max_public_pages": 5,
        },
    },
    {
        "code": "pro",
        "name": "Pro",
        "description": "Advanced features for established businesses",
        "display_order": 4,
        "version": {
            "name": "Pro Plan",
            "price_monthly_cents": 9900,
            "price_yearly_cents": 99000,
            "is_public": True,
            "is_most_popular": False,
            "show_price": True,
            "trial_days": 14,
        },
        "boolean_features": {
            "email_enabled": True,
            "online_booking": True,
            "recurring_appointments": True,
            "payment_processing": True,
            "mobile_app_access": True,
            "sms_enabled": True,
            "custom_domain": True,
            "integrations_enabled": True,
            "api_access": True,
            "masked_calling_enabled": True,
            "advanced_reporting": True,
            "team_permissions": True,
            "audit_logs": True,
            "custom_branding": True,
            "can_use_email_templates": True,
            "can_use_automations": True,
            "can_use_tasks": True,
            "can_create_automations": True,
            "can_process_refunds": True,
            "can_use_calendar_sync": True,
            "can_export_data": True,
            "can_add_video_conferencing": True,
            "can_create_packages": True,
            "can_use_pos": True,
            "can_use_contracts": True,
        },
        "integer_features": {
            "max_users": 25,
            "max_resources": 25,
            "max_locations": 10,
            "max_services": 250,
            "max_customers": 50000,
            "max_appointments_per_month": 10000,
            "max_email_per_month": 50000,
            "max_sms_per_month": 10000,
            "max_storage_mb": 50000,
            "max_api_calls_per_day": 50000,
            "max_public_pages": 10,
        },
    },
    {
        "code": "enterprise",
        "name": "Enterprise",
        "description": "Unlimited power for large organizations",
        "display_order": 5,
        "version": {
            "name": "Enterprise Plan",
            "price_monthly_cents": 19900,
            "price_yearly_cents": 199000,
            "is_public": True,
            "is_most_popular": False,
            "show_price": False,  # "Contact us" pricing
            "trial_days": 30,
        },
        "boolean_features": {
            "email_enabled": True,
            "online_booking": True,
            "recurring_appointments": True,
            "payment_processing": True,
            "mobile_app_access": True,
            "sms_enabled": True,
            "custom_domain": True,
            "integrations_enabled": True,
            "api_access": True,
            "masked_calling_enabled": True,
            "advanced_reporting": True,
            "team_permissions": True,
            "audit_logs": True,
            "custom_branding": True,
            "white_label": True,
            "remove_branding": True,
            "multi_location": True,
            "priority_support": True,
            "dedicated_account_manager": True,
            "sla_guarantee": True,
            "can_use_email_templates": True,
            "can_use_automations": True,
            "can_use_tasks": True,
            "can_create_automations": True,
            "can_process_refunds": True,
            "can_use_calendar_sync": True,
            "can_export_data": True,
            "can_add_video_conferencing": True,
            "can_create_packages": True,
            "can_use_pos": True,
            "can_use_contracts": True,
            "can_manage_oauth": True,
        },
        "integer_features": {
            # All unlimited (None)
            "max_users": None,
            "max_resources": None,
            "max_locations": None,
            "max_services": None,
            "max_customers": None,
            "max_appointments_per_month": None,
            "max_email_per_month": None,
            "max_sms_per_month": None,
            "max_storage_mb": None,
            "max_api_calls_per_day": None,
            "max_public_pages": None,
        },
    },
]


# =============================================================================
# Add-On Definitions
# =============================================================================

ADDONS = [
    {
        "code": "sms_boost_5000",
        "name": "SMS Boost Pack",
        "description": "Add 5,000 SMS messages per month to your quota",
        "price_monthly_cents": 2500,
        "price_one_time_cents": 0,  # Recurring only
        "is_stackable": True,  # Can purchase multiple
        "features": [
            {"code": "max_sms_per_month", "int_value": 5000},
        ],
    },
    {
        "code": "extra_locations_5",
        "name": "Extra Locations Pack",
        "description": "Add 5 additional business locations",
        "price_monthly_cents": 2900,
        "price_one_time_cents": 0,  # Recurring only
        "is_stackable": True,
        "features": [
            {"code": "max_locations", "int_value": 5},
        ],
    },
    {
        "code": "advanced_reporting_addon",
        "name": "Advanced Reporting",
        "description": "Unlock advanced analytics and reporting features",
        "price_monthly_cents": 1500,
        "price_one_time_cents": 0,  # Recurring only
        "is_stackable": False,
        "features": [
            {"code": "advanced_reporting", "bool_value": True},
        ],
    },
    {
        "code": "api_access_addon",
        "name": "API + Webhooks",
        "description": "Enable API access and webhook integrations",
        "price_monthly_cents": 2000,
        "price_one_time_cents": 0,  # Recurring only
        "is_stackable": False,
        "features": [
            {"code": "api_access", "bool_value": True},
            {"code": "integrations_enabled", "bool_value": True},
        ],
    },
    {
        "code": "masked_calling_addon",
        "name": "Masked Calling",
        "description": "Enable masked calling for privacy protection",
        "price_monthly_cents": 3900,
        "price_one_time_cents": 0,  # Recurring only
        "is_stackable": False,
        "features": [
            {"code": "masked_calling_enabled", "bool_value": True},
        ],
    },
    {
        "code": "white_label_addon",
        "name": "White Label",
        "description": "Remove all SmoothSchedule branding",
        "price_monthly_cents": 9900,
        "price_one_time_cents": 0,  # Recurring only
        "is_stackable": False,
        "features": [
            {"code": "white_label", "bool_value": True},
            {"code": "remove_branding", "bool_value": True},
        ],
    },
]


class Command(BaseCommand):
    help = "Seed the billing catalog with Plans, Features, and AddOns"

    def add_arguments(self, parser):
        parser.add_argument(
            "--drop-existing",
            action="store_true",
            help="Drop existing plans and add-ons before seeding (keeps features)",
        )

    def handle(self, *args, **options):
        self.stdout.write("Starting billing catalog seeding...")

        # Initialize subscription data storage
        self._subscription_data = []

        with transaction.atomic():
            # Step 1: Seed features (always update/create)
            self._seed_features()

            # Step 2: Optionally drop existing plans and add-ons
            if options["drop_existing"]:
                self._drop_existing()

            # Step 3: Seed plans with versions and features
            self._seed_plans()

            # Step 4: Seed add-ons with features
            self._seed_addons()

            # Step 5: Restore subscriptions if we dropped plans
            if options["drop_existing"]:
                self._restore_subscriptions()

        self.stdout.write(self.style.SUCCESS("Billing catalog seeding complete!"))

    def _seed_features(self):
        """Create or update all features."""
        self.stdout.write("  Seeding features...")
        created_count = 0
        updated_count = 0

        # First pass: create/update features without depends_on
        for feature_data in FEATURES:
            defaults = {
                "name": feature_data["name"],
                "description": feature_data["description"],
                "feature_type": feature_data["feature_type"],
                "category": feature_data.get("category", "advanced"),
                "tenant_field_name": feature_data.get("tenant_field_name", ""),
                "display_order": feature_data.get("display_order", 100),
                "is_overridable": feature_data.get("is_overridable", True),
            }
            obj, created = Feature.objects.update_or_create(
                code=feature_data["code"],
                defaults=defaults,
            )
            if created:
                created_count += 1
            else:
                updated_count += 1

        # Second pass: set depends_on relationships
        for feature_data in FEATURES:
            depends_on_code = feature_data.get("depends_on")
            if depends_on_code:
                feature = Feature.objects.get(code=feature_data["code"])
                parent_feature = Feature.objects.get(code=depends_on_code)
                feature.depends_on = parent_feature
                feature.save(update_fields=["depends_on"])

        self.stdout.write(f"    Features: {created_count} created, {updated_count} updated")

    def _drop_existing(self):
        """
        Drop existing plans and add-ons (preserves features).
        Also stores subscription data for later restoration.
        """
        from smoothschedule.billing.models import Subscription, SubscriptionAddOn

        self.stdout.write("  Saving subscription data for restoration...")

        # Store full subscription data for recreation
        self._subscription_data = []
        for sub in Subscription.objects.select_related('plan_version__plan', 'business'):
            if sub.plan_version and sub.plan_version.plan:
                sub_data = {
                    'business_id': sub.business_id,
                    'plan_code': sub.plan_version.plan.code,
                    'status': sub.status,
                    'started_at': sub.started_at,
                    'current_period_start': sub.current_period_start,
                    'current_period_end': sub.current_period_end,
                    'trial_ends_at': sub.trial_ends_at,
                    'canceled_at': sub.canceled_at,
                    'stripe_subscription_id': sub.stripe_subscription_id,
                }
                self._subscription_data.append(sub_data)

        self.stdout.write(f"    Saved {len(self._subscription_data)} subscriptions for restoration")

        self.stdout.write("  Dropping existing data...")

        # Delete subscriptions first (this cascades to SubscriptionAddOn)
        sub_count = Subscription.objects.count()
        Subscription.objects.all().delete()
        self.stdout.write(f"    Deleted {sub_count} subscriptions")

        # Delete in order to respect foreign keys
        # Note: This will cascade delete PlanFeatures, AddOnFeatures, etc.
        addon_count = AddOnProduct.objects.count()
        AddOnProduct.objects.all().delete()
        self.stdout.write(f"    Deleted {addon_count} add-on products")

        plan_version_count = PlanVersion.objects.count()
        PlanVersion.objects.all().delete()
        self.stdout.write(f"    Deleted {plan_version_count} plan versions")

        plan_count = Plan.objects.count()
        Plan.objects.all().delete()
        self.stdout.write(f"    Deleted {plan_count} plans")

    def _seed_plans(self):
        """Create or update all plans with their versions and features."""
        self.stdout.write("  Seeding plans...")

        for plan_data in PLANS:
            # Create or update the Plan
            plan, plan_created = Plan.objects.update_or_create(
                code=plan_data["code"],
                defaults={
                    "name": plan_data["name"],
                    "description": plan_data["description"],
                    "display_order": plan_data["display_order"],
                    "is_active": True,
                },
            )

            # Create or update the PlanVersion (version 1)
            version_data = plan_data["version"]
            plan_version, pv_created = PlanVersion.objects.update_or_create(
                plan=plan,
                version=1,
                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["is_public"],
                    "is_legacy": False,
                    "is_most_popular": version_data["is_most_popular"],
                    "show_price": version_data["show_price"],
                    "trial_days": version_data["trial_days"],
                    # Stripe IDs - TODO: Add when Stripe products are created
                    "stripe_product_id": "",
                    "stripe_price_id_monthly": "",
                    "stripe_price_id_yearly": "",
                },
            )

            # Create PlanFeatures
            self._create_plan_features(
                plan_version,
                plan_data["boolean_features"],
                plan_data["integer_features"],
            )

            status = "created" if plan_created else "updated"
            self.stdout.write(f"    Plan '{plan.code}' {status}")

    def _create_plan_features(self, plan_version, boolean_features, integer_features):
        """Create PlanFeature records for a plan version."""
        # Clear existing features for this version
        PlanFeature.objects.filter(plan_version=plan_version).delete()

        # Add boolean features
        for code, value in boolean_features.items():
            feature = Feature.objects.get(code=code)
            PlanFeature.objects.create(
                plan_version=plan_version,
                feature=feature,
                bool_value=value,
                int_value=None,
            )

        # Add integer features
        for code, value in integer_features.items():
            feature = Feature.objects.get(code=code)
            PlanFeature.objects.create(
                plan_version=plan_version,
                feature=feature,
                bool_value=None,
                int_value=value,  # Can be None for unlimited
            )

    def _seed_addons(self):
        """Create or update all add-on products with their features."""
        self.stdout.write("  Seeding add-ons...")

        for addon_data in ADDONS:
            # Create or update the AddOnProduct
            addon, addon_created = AddOnProduct.objects.update_or_create(
                code=addon_data["code"],
                defaults={
                    "name": addon_data["name"],
                    "description": addon_data["description"],
                    "price_monthly_cents": addon_data["price_monthly_cents"],
                    "price_one_time_cents": addon_data.get("price_one_time_cents"),
                    "is_stackable": addon_data["is_stackable"],
                    "is_active": True,
                    # Stripe IDs - TODO: Add when Stripe products are created
                    "stripe_product_id": "",
                    "stripe_price_id": "",
                },
            )

            # Create AddOnFeatures
            self._create_addon_features(addon, addon_data["features"])

            status = "created" if addon_created else "updated"
            self.stdout.write(f"    Add-on '{addon.code}' {status}")

    def _create_addon_features(self, addon, features):
        """Create AddOnFeature records for an add-on."""
        # Clear existing features for this add-on
        AddOnFeature.objects.filter(addon=addon).delete()

        for feature_data in features:
            feature = Feature.objects.get(code=feature_data["code"])
            AddOnFeature.objects.create(
                addon=addon,
                feature=feature,
                bool_value=feature_data.get("bool_value"),
                int_value=feature_data.get("int_value"),
            )

    def _restore_subscriptions(self):
        """Recreate subscriptions after reseeding plans."""
        from smoothschedule.billing.models import Subscription

        self.stdout.write("  Recreating subscriptions...")

        if not self._subscription_data:
            self.stdout.write("    No subscriptions to restore")
            return

        restored_count = 0
        failed_count = 0

        for sub_data in self._subscription_data:
            plan_code = sub_data['plan_code']
            business_id = sub_data['business_id']

            try:
                # Find the new plan version for this plan code
                plan = Plan.objects.get(code=plan_code)
                # Get the active (non-legacy) version
                plan_version = PlanVersion.objects.filter(
                    plan=plan,
                    is_legacy=False,
                ).order_by('-version').first()

                if plan_version:
                    # Recreate the subscription
                    Subscription.objects.create(
                        business_id=business_id,
                        plan_version=plan_version,
                        status=sub_data['status'],
                        started_at=sub_data['started_at'],
                        current_period_start=sub_data['current_period_start'],
                        current_period_end=sub_data['current_period_end'],
                        trial_ends_at=sub_data['trial_ends_at'],
                        canceled_at=sub_data['canceled_at'],
                        stripe_subscription_id=sub_data['stripe_subscription_id'],
                    )
                    restored_count += 1
                else:
                    self.stdout.write(
                        self.style.WARNING(
                            f"    No active version found for plan '{plan_code}' "
                            f"(business {business_id})"
                        )
                    )
                    failed_count += 1

            except Plan.DoesNotExist:
                self.stdout.write(
                    self.style.WARNING(
                        f"    Plan '{plan_code}' not found for business {business_id}"
                    )
                )
                failed_count += 1
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(
                        f"    Error restoring subscription for business {business_id}: {e}"
                    )
                )
                failed_count += 1

        self.stdout.write(
            f"    Subscriptions: {restored_count} recreated, {failed_count} failed"
        )
