# Generated migration to fix subscription constraints

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


class Migration(migrations.Migration):

    dependencies = [
        ('igny8_core_auth', '0011_remove_subscription_payment_method'),
    ]

    operations = [
        # Add unique constraint on tenant_id at database level
        migrations.RunSQL(
            sql="""
            CREATE UNIQUE INDEX IF NOT EXISTS igny8_subscriptions_tenant_id_unique 
            ON igny8_subscriptions(tenant_id);
            """,
            reverse_sql="""
            DROP INDEX IF EXISTS igny8_subscriptions_tenant_id_unique;
            """
        ),
        
        # Make plan field required (non-nullable)
        # First set default plan (ID 1 - Free Plan) for any null values
        migrations.RunSQL(
            sql="""
            UPDATE igny8_subscriptions 
            SET plan_id = 1 
            WHERE plan_id IS NULL;
            """,
            reverse_sql=migrations.RunSQL.noop
        ),
        
        # Now alter the field to be non-nullable
        migrations.AlterField(
            model_name='subscription',
            name='plan',
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.PROTECT,
                related_name='subscriptions',
                to='igny8_core_auth.plan',
                help_text='Subscription plan (tracks historical plan even if account changes plan)'
            ),
        ),
    ]
