# Migration to add database constraints and indexes for data integrity
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('billing', '0009_add_missing_payment_methods'),
        ('igny8_core_auth', '0011_remove_subscription_payment_method'),
    ]

    operations = [
        # Add DB index on invoice_number for fast lookups
        migrations.AlterField(
            model_name='invoice',
            name='invoice_number',
            field=models.CharField(db_index=True, max_length=50, unique=True),
        ),
        
        # Add index on Payment.status for filtering
        migrations.AlterField(
            model_name='payment',
            name='status',
            field=models.CharField(
                choices=[
                    ('pending_approval', 'Pending Approval'),
                    ('succeeded', 'Succeeded'),
                    ('failed', 'Failed'),
                    ('refunded', 'Refunded')
                ],
                db_index=True,
                default='pending_approval',
                max_length=20
            ),
        ),
        
        # Add partial unique index on AccountPaymentMethod for single default per account
        # This prevents multiple is_default=True per account
        migrations.RunSQL(
            sql="""
                CREATE UNIQUE INDEX billing_account_payment_method_single_default 
                ON igny8_account_payment_methods (tenant_id) 
                WHERE is_default = true AND is_enabled = true;
            """,
            reverse_sql="""
                DROP INDEX IF EXISTS billing_account_payment_method_single_default;
            """
        ),
        
        # Add composite index on Payment for common queries
        migrations.AddIndex(
            model_name='payment',
            index=models.Index(
                fields=['account', 'status', '-created_at'],
                name='payment_account_status_created_idx'
            ),
        ),
    ]
