# Generated migration for demo reseed periodic task

from django.db import migrations


def create_demo_reseed_task(apps, schema_editor):
    """Create the periodic task for daily demo reseed."""
    try:
        CrontabSchedule = apps.get_model('django_celery_beat', 'CrontabSchedule')
        PeriodicTask = apps.get_model('django_celery_beat', 'PeriodicTask')

        # Create crontab schedule for midnight UTC
        schedule, _ = CrontabSchedule.objects.get_or_create(
            minute='0',
            hour='0',
            day_of_week='*',
            day_of_month='*',
            month_of_year='*',
            defaults={'timezone': 'UTC'}
        )

        # Create periodic task
        PeriodicTask.objects.update_or_create(
            name='reseed-demo-tenant-daily',
            defaults={
                'task': 'smoothschedule.scheduling.schedule.tasks.reseed_demo_tenant',
                'crontab': schedule,
                'enabled': True,
                'description': 'Daily reseed of demo tenant for sales demonstrations',
            }
        )
    except Exception:
        # django_celery_beat may not be installed/migrated yet
        pass


def remove_demo_reseed_task(apps, schema_editor):
    """Remove the periodic task."""
    try:
        PeriodicTask = apps.get_model('django_celery_beat', 'PeriodicTask')
        PeriodicTask.objects.filter(name='reseed-demo-tenant-daily').delete()
    except Exception:
        pass


class Migration(migrations.Migration):

    dependencies = [
        ('schedule', '0039_remove_emailtemplate'),
    ]

    operations = [
        migrations.RunPython(create_demo_reseed_task, remove_demo_reseed_task),
    ]
