"""
Management command to set up periodic Celery tasks for billing operations.

Run this after deployment:
    python manage.py setup_billing_tasks
"""

from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = 'Set up periodic Celery Beat tasks for billing operations'

    def handle(self, *args, **options):
        from django_celery_beat.models import PeriodicTask, CrontabSchedule

        self.stdout.write('Setting up billing periodic tasks...')

        # Create crontab schedule
        # Daily at 1 AM - check custom tier grace periods
        schedule_1am, _ = CrontabSchedule.objects.get_or_create(
            minute='0',
            hour='1',
            day_of_week='*',
            day_of_month='*',
            month_of_year='*',
        )

        # Create periodic task
        task, created = PeriodicTask.objects.update_or_create(
            name='billing-check-grace-periods',
            defaults={
                'task': 'smoothschedule.billing.tasks.check_subscription_grace_periods',
                'crontab': schedule_1am,
                'description': 'Check custom tier grace periods and manage subscription lapses (runs daily at 1 AM)',
                'enabled': True,
            }
        )

        status = 'Created' if created else 'Updated'
        self.stdout.write(self.style.SUCCESS(f"  {status}: {task.name}"))

        self.stdout.write(self.style.SUCCESS('\nBilling tasks set up successfully!'))
        self.stdout.write('\nTasks configured:')
        self.stdout.write('  - billing-check-grace-periods: Daily at 1 AM')
        self.stdout.write('    - Clears grace period when subscription becomes active')
        self.stdout.write('    - Starts grace period when subscription becomes inactive')
        self.stdout.write('    - Deletes custom tiers after 30-day grace period expires')
