"""
Management command to seed default subscription plans.

Usage:
    python manage.py seed_subscription_plans
    python manage.py seed_subscription_plans --force  # Override existing plans
"""

from django.core.management.base import BaseCommand
from smoothschedule.platform.admin.models import SubscriptionPlan


class Command(BaseCommand):
    help = 'Seeds default subscription plans for the platform'

    def add_arguments(self, parser):
        parser.add_argument(
            '--force',
            action='store_true',
            help='Override existing plans with the same name',
        )

    def handle(self, *args, **options):
        force = options['force']

        plans = [
            # Free Tier - No payments included (requires Payments add-on)
            {
                'name': 'Free',
                'description': 'Perfect for getting started. Try out the core features with no commitment.',
                'plan_type': 'base',
                'price_monthly': None,
                'price_yearly': None,
                'features': [
                    'Up to 2 team members',
                    'Up to 5 resources',
                    '50 appointments per month',
                    'Basic scheduling',
                    'Email notifications',
                    'Mobile-friendly booking page',
                    'Community support',
                ],
                'limits': {
                    'max_users': 2,
                    'max_resources': 5,
                    'max_appointments': 50,
                    'max_services': 10,
                    'max_automated_tasks': 0,
                    'max_email_templates': 3,
                },
                'permissions': {
                    'can_accept_payments': False,  # Requires Payments add-on
                    'sms_reminders': False,
                    'advanced_reporting': False,
                    'priority_support': False,
                    'can_use_custom_domain': False,
                    'can_create_plugins': False,
                    'can_white_label': False,
                    'can_api_access': False,
                    'can_use_masked_phone_numbers': False,
                    'can_use_email_templates': True,
                    'can_customize_booking_page': False,
                    'can_export_data': False,
                },
                'transaction_fee_percent': 0,  # No payments
                'transaction_fee_fixed': 0,
                'sms_enabled': False,
                'masked_calling_enabled': False,
                'proxy_number_enabled': False,
                'is_active': True,
                'is_public': True,
                'is_most_popular': False,
                'show_price': True,
            },
            # Starter Tier - Stripe charges 2.9% + $0.30, we charge 4% + $0.40
            {
                'name': 'Starter',
                'description': 'Great for small businesses ready to grow. Essential tools to manage your appointments.',
                'plan_type': 'base',
                'price_monthly': 19.00,
                'price_yearly': 190.00,
                'features': [
                    'Up to 5 team members',
                    'Up to 15 resources',
                    'Unlimited appointments',
                    'Online payments (4% + $0.40)',
                    'SMS reminders',
                    'Custom booking page colors',
                    'Google Calendar sync',
                    'Basic analytics',
                    'Email support',
                ],
                'limits': {
                    'max_users': 5,
                    'max_resources': 15,
                    'max_appointments': -1,  # Unlimited
                    'max_services': 25,
                    'max_automated_tasks': 3,
                    'max_email_templates': 10,
                },
                'permissions': {
                    'can_accept_payments': True,
                    'sms_reminders': True,
                    'advanced_reporting': False,
                    'priority_support': False,
                    'can_use_custom_domain': False,
                    'can_create_plugins': False,
                    'can_white_label': False,
                    'can_api_access': False,
                    'can_use_masked_phone_numbers': False,
                    'can_use_email_templates': True,
                    'can_customize_booking_page': True,
                    'can_export_data': True,
                },
                'transaction_fee_percent': 4.0,  # Stripe: 2.9%, our margin: 1.1%
                'transaction_fee_fixed': 40,  # 40 cents (Stripe: 30¢, our margin: 10¢)
                'sms_enabled': True,
                'sms_price_per_message_cents': 3,
                'masked_calling_enabled': False,
                'proxy_number_enabled': False,
                'is_active': True,
                'is_public': True,
                'is_most_popular': False,
                'show_price': True,
            },
            # Professional Tier - Stripe charges 2.9% + $0.30, we charge 3.5% + $0.35
            {
                'name': 'Professional',
                'description': 'For growing teams that need powerful automation and customization.',
                'plan_type': 'base',
                'price_monthly': 49.00,
                'price_yearly': 490.00,
                'features': [
                    'Up to 15 team members',
                    'Unlimited resources',
                    'Unlimited appointments',
                    'Lower payment fees (3.5% + $0.35)',
                    'SMS & masked calling',
                    'Custom domain',
                    'Advanced analytics',
                    'Automated workflows',
                    'Custom email templates',
                    'API access',
                    'Priority email support',
                ],
                'limits': {
                    'max_users': 15,
                    'max_resources': -1,  # Unlimited
                    'max_appointments': -1,
                    'max_services': -1,
                    'max_automated_tasks': 10,
                    'max_email_templates': -1,
                },
                'permissions': {
                    'can_accept_payments': True,
                    'sms_reminders': True,
                    'advanced_reporting': True,
                    'priority_support': True,
                    'can_use_custom_domain': True,
                    'can_create_plugins': False,
                    'can_white_label': False,
                    'can_api_access': True,
                    'can_use_masked_phone_numbers': True,
                    'can_use_email_templates': True,
                    'can_customize_booking_page': True,
                    'can_export_data': True,
                },
                'transaction_fee_percent': 3.5,  # Stripe: 2.9%, our margin: 0.6%
                'transaction_fee_fixed': 35,  # 35 cents (Stripe: 30¢, our margin: 5¢)
                'sms_enabled': True,
                'sms_price_per_message_cents': 3,
                'masked_calling_enabled': True,
                'masked_calling_price_per_minute_cents': 5,
                'proxy_number_enabled': True,
                'proxy_number_monthly_fee_cents': 200,
                'default_auto_reload_enabled': True,
                'default_auto_reload_threshold_cents': 1000,
                'default_auto_reload_amount_cents': 2500,
                'is_active': True,
                'is_public': True,
                'is_most_popular': True,
                'show_price': True,
            },
            # Business Tier - Stripe charges 2.9% + $0.30, we charge 3.25% + $0.32
            {
                'name': 'Business',
                'description': 'For established businesses with multiple locations or large teams.',
                'plan_type': 'base',
                'price_monthly': 99.00,
                'price_yearly': 990.00,
                'features': [
                    'Up to 50 team members',
                    'Unlimited resources',
                    'Unlimited appointments',
                    'Lower payment fees (3.25% + $0.32)',
                    'All communication features',
                    'Multiple custom domains',
                    'White-label option',
                    'Custom plugins',
                    'Advanced automation',
                    'Dedicated onboarding',
                    'Priority phone support',
                ],
                'limits': {
                    'max_users': 50,
                    'max_resources': -1,
                    'max_appointments': -1,
                    'max_services': -1,
                    'max_automated_tasks': 25,
                    'max_email_templates': -1,
                },
                'permissions': {
                    'can_accept_payments': True,
                    'sms_reminders': True,
                    'advanced_reporting': True,
                    'priority_support': True,
                    'can_use_custom_domain': True,
                    'can_create_plugins': True,
                    'can_white_label': True,
                    'can_api_access': True,
                    'can_use_masked_phone_numbers': True,
                    'can_use_email_templates': True,
                    'can_customize_booking_page': True,
                    'can_export_data': True,
                },
                'transaction_fee_percent': 3.25,  # Stripe: 2.9%, our margin: 0.35%
                'transaction_fee_fixed': 32,  # 32 cents (Stripe: 30¢, our margin: 2¢)
                'sms_enabled': True,
                'sms_price_per_message_cents': 2,
                'masked_calling_enabled': True,
                'masked_calling_price_per_minute_cents': 4,
                'proxy_number_enabled': True,
                'proxy_number_monthly_fee_cents': 150,
                'default_auto_reload_enabled': True,
                'default_auto_reload_threshold_cents': 2000,
                'default_auto_reload_amount_cents': 5000,
                'is_active': True,
                'is_public': True,
                'is_most_popular': False,
                'show_price': True,
            },
            # Enterprise Tier - Stripe charges 2.9% + $0.30, we charge 3% + $0.30 (minimal margin)
            {
                'name': 'Enterprise',
                'description': 'Custom solutions for large organizations with complex needs.',
                'plan_type': 'base',
                'price_monthly': None,  # Contact us
                'price_yearly': None,
                'features': [
                    'Unlimited team members',
                    'Unlimited everything',
                    'Lowest payment fees (3% + $0.30)',
                    'Dedicated infrastructure',
                    'Custom integrations',
                    'SSO/SAML support',
                    'SLA guarantee',
                    'Dedicated account manager',
                    '24/7 priority support',
                    'Custom contracts',
                ],
                'limits': {
                    'max_users': -1,
                    'max_resources': -1,
                    'max_appointments': -1,
                    'max_services': -1,
                    'max_automated_tasks': -1,
                    'max_email_templates': -1,
                },
                'permissions': {
                    'can_accept_payments': True,
                    'sms_reminders': True,
                    'advanced_reporting': True,
                    'priority_support': True,
                    'can_use_custom_domain': True,
                    'can_create_plugins': True,
                    'can_white_label': True,
                    'can_api_access': True,
                    'can_use_masked_phone_numbers': True,
                    'can_use_email_templates': True,
                    'can_customize_booking_page': True,
                    'can_export_data': True,
                    'sso_enabled': True,
                    'dedicated_support': True,
                },
                'transaction_fee_percent': 3.0,  # Stripe: 2.9%, our margin: 0.1%
                'transaction_fee_fixed': 30,  # 30 cents (Stripe: 30¢, break-even)
                'sms_enabled': True,
                'sms_price_per_message_cents': 2,
                'masked_calling_enabled': True,
                'masked_calling_price_per_minute_cents': 3,
                'proxy_number_enabled': True,
                'proxy_number_monthly_fee_cents': 100,
                'default_auto_reload_enabled': True,
                'default_auto_reload_threshold_cents': 5000,
                'default_auto_reload_amount_cents': 10000,
                'is_active': True,
                'is_public': True,
                'is_most_popular': False,
                'show_price': False,  # Contact us
            },
            # Add-ons
            {
                'name': 'Extra Team Members',
                'description': 'Add more team members to your plan.',
                'plan_type': 'addon',
                'price_monthly': 5.00,
                'price_yearly': 50.00,
                'features': [
                    'Add 1 additional team member',
                    'Full feature access for new member',
                ],
                'limits': {
                    'additional_users': 1,
                },
                'permissions': {},
                'transaction_fee_percent': 0,
                'transaction_fee_fixed': 0,
                'is_active': True,
                'is_public': True,
                'show_price': True,
            },
            # SMS Notifications Add-on - enables SMS reminders for tiers without it
            {
                'name': 'SMS Notifications',
                'description': 'Send SMS appointment reminders and notifications to your customers.',
                'plan_type': 'addon',
                'price_monthly': 10.00,
                'price_yearly': 100.00,
                'features': [
                    'SMS appointment reminders',
                    'Custom SMS templates',
                    'Two-way SMS messaging',
                    'Pay-as-you-go credits ($0.03/msg)',
                ],
                'limits': {},
                'permissions': {
                    'sms_reminders': True,
                },
                'sms_enabled': True,
                'sms_price_per_message_cents': 3,
                'transaction_fee_percent': 0,
                'transaction_fee_fixed': 0,
                'is_active': True,
                'is_public': True,
                'show_price': True,
                # Note: Only show to businesses without sms_reminders permission
            },
            {
                'name': 'SMS Bundle',
                'description': 'Bulk SMS credits at a discounted rate. Requires SMS Notifications.',
                'plan_type': 'addon',
                'price_monthly': 20.00,
                'price_yearly': None,
                'features': [
                    '1,000 SMS credits',
                    'Never expires',
                    '33% savings vs pay-as-you-go',
                ],
                'limits': {
                    'sms_credits': 1000,
                },
                'permissions': {},
                'transaction_fee_percent': 0,
                'transaction_fee_fixed': 0,
                'is_active': True,
                'is_public': True,
                'show_price': True,
                # Note: Only show to businesses with sms_reminders permission
            },
            # Masked Calling Add-on - enables anonymous calling between customers and staff
            {
                'name': 'Masked Calling',
                'description': 'Enable anonymous phone calls between your customers and staff.',
                'plan_type': 'addon',
                'price_monthly': 15.00,
                'price_yearly': 150.00,
                'features': [
                    'Anonymous customer-staff calls',
                    'Privacy protection for both parties',
                    'Call recording (optional)',
                    'Pay-as-you-go minutes ($0.05/min)',
                    'Includes 1 proxy phone number',
                ],
                'limits': {},
                'permissions': {
                    'can_use_masked_phone_numbers': True,
                },
                'masked_calling_enabled': True,
                'masked_calling_price_per_minute_cents': 5,
                'proxy_number_enabled': True,
                'proxy_number_monthly_fee_cents': 0,  # First number included
                'transaction_fee_percent': 0,
                'transaction_fee_fixed': 0,
                'is_active': True,
                'is_public': True,
                'show_price': True,
                # Note: Only show to businesses without can_use_masked_phone_numbers permission
            },
            {
                'name': 'Additional Proxy Number',
                'description': 'Add a dedicated phone number for masked calling.',
                'plan_type': 'addon',
                'price_monthly': 2.00,
                'price_yearly': 20.00,
                'features': [
                    '1 dedicated phone number',
                    'US or Canadian number',
                    'Masked calling support',
                ],
                'limits': {
                    'additional_proxy_numbers': 1,
                },
                'permissions': {},
                'transaction_fee_percent': 0,
                'transaction_fee_fixed': 0,
                'is_active': True,
                'is_public': True,
                'show_price': True,
                # Note: Only show to businesses WITH can_use_masked_phone_numbers permission
                # (either from tier or Masked Calling addon)
            },
            {
                'name': 'White Label',
                'description': 'Remove all SmoothSchedule branding from your booking pages.',
                'plan_type': 'addon',
                'price_monthly': 29.00,
                'price_yearly': 290.00,
                'features': [
                    'Remove SmoothSchedule branding',
                    'Custom footer text',
                    'Custom email sender name',
                ],
                'limits': {},
                'permissions': {
                    'can_white_label': True,
                },
                'transaction_fee_percent': 0,
                'transaction_fee_fixed': 0,
                'is_active': True,
                'is_public': True,
                'show_price': True,
            },
            # Online Payments Add-on - for Free tier users who want payment processing
            # Covers Stripe's $2/mo connected account fee + transaction fees
            {
                'name': 'Online Payments',
                'description': 'Accept online payments from your customers. For businesses on Free tier.',
                'plan_type': 'addon',
                'price_monthly': 5.00,
                'price_yearly': 50.00,
                'features': [
                    'Accept credit/debit cards',
                    'Stripe Connect integration',
                    'Automatic payouts',
                    'Payment analytics',
                    '5% + $0.50 per transaction',
                ],
                'limits': {},
                'permissions': {
                    'can_accept_payments': True,
                },
                'transaction_fee_percent': 5.0,  # Stripe: 2.9%, our margin: 2.1% (covers $2/mo account fee)
                'transaction_fee_fixed': 50,  # 50 cents (Stripe: 30¢, our margin: 20¢)
                'is_active': True,
                'is_public': True,
                'show_price': True,
                # Note: This addon should only be shown to businesses without can_accept_payments
                # The frontend/backend should filter visibility based on current permissions
            },
        ]

        created_count = 0
        updated_count = 0
        skipped_count = 0

        for plan_data in plans:
            existing = SubscriptionPlan.objects.filter(name=plan_data['name']).first()

            if existing:
                if force:
                    for key, value in plan_data.items():
                        setattr(existing, key, value)
                    existing.save()
                    updated_count += 1
                    self.stdout.write(
                        self.style.WARNING(f"Updated: {plan_data['name']}")
                    )
                else:
                    skipped_count += 1
                    self.stdout.write(
                        self.style.NOTICE(f"Skipped (exists): {plan_data['name']}")
                    )
            else:
                SubscriptionPlan.objects.create(**plan_data)
                created_count += 1
                self.stdout.write(
                    self.style.SUCCESS(f"Created: {plan_data['name']}")
                )

        self.stdout.write('')
        self.stdout.write(
            self.style.SUCCESS(
                f"Done! Created: {created_count}, Updated: {updated_count}, Skipped: {skipped_count}"
            )
        )
