# Generated by Django 6.1 on 2026-08-15 12:26

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


def migrate_existing_access(apps, schema_editor):
    Enrollment = apps.get_model('courses', 'Enrollment')
    LegacyLicense = apps.get_model('courses', 'SpotplayerLicense')
    Order = apps.get_model('courses', 'Order')
    existing = [
        Enrollment(user_id=item.user_id, course_id=item.course_id, source='Legacy')
        for item in LegacyLicense.objects.all().iterator()
    ]
    existing.extend(
        Enrollment(user_id=order.user_id, course_id=order.course_id, source='Payment')
        for order in Order.objects.filter(status='Completed').iterator()
    )
    Enrollment.objects.bulk_create(existing, ignore_conflicts=True)


class Migration(migrations.Migration):

    dependencies = [
        ('courses', '0009_order_gateway_authority_order_gateway_reference_and_more'),
    ]

    operations = [
        migrations.AlterField(
            model_name='course',
            name='course_id',
            field=models.CharField(max_length=100, unique=True, verbose_name='کد یکتای دوره'),
        ),
        migrations.CreateModel(
            name='Enrollment',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('source', models.CharField(choices=[('Payment', 'خرید'), ('Admin', 'فعال\u200cسازی مدیر'), ('Free', 'دوره رایگان'), ('Legacy', 'انتقال از سامانه قبلی')], default='Admin', max_length=20)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('course', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='enrollments', to='courses.course')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='enrollments', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'verbose_name': 'ثبت\u200cنام دوره',
                'verbose_name_plural': 'ثبت\u200cنام\u200cهای دوره',
                'constraints': [models.UniqueConstraint(fields=('course', 'user'), name='unique_course_enrollment_per_user')],
            },
        ),
        migrations.RunPython(migrate_existing_access, migrations.RunPython.noop),
    ]
