# Generated migration to add subscription FK to Invoice and fix Payment status default
from django.db import migrations, models
import django.db.models.deletion


def populate_subscription_from_metadata(apps, schema_editor):
    """Populate subscription FK from metadata for existing invoices"""
    # Use raw SQL to avoid model field issues during migration
    from django.db import connection
    
    with connection.cursor() as cursor:
        # Get invoices with subscription_id in metadata
        cursor.execute("""
            SELECT id, metadata 
            FROM igny8_invoices 
            WHERE metadata::text LIKE '%subscription_id%'
        """)
        
        updated_count = 0
        for invoice_id, metadata in cursor.fetchall():
            if metadata and isinstance(metadata, dict) and 'subscription_id' in metadata:
                try:
                    sub_id = int(metadata['subscription_id'])
                    # Check if subscription exists
                    cursor.execute(
                        "SELECT id FROM igny8_subscriptions WHERE id = %s",
                        [sub_id]
                    )
                    if cursor.fetchone():
                        # Update invoice with subscription FK
                        cursor.execute(
                            "UPDATE igny8_invoices SET subscription_id = %s WHERE id = %s",
                            [sub_id, invoice_id]
                        )
                        updated_count += 1
                except (ValueError, KeyError) as e:
                    print(f"Could not populate subscription for invoice {invoice_id}: {e}")
        
        print(f"Populated subscription FK for {updated_count} invoices")


class Migration(migrations.Migration):

    dependencies = [
        ('billing', '0007_simplify_payment_statuses'),
        ('igny8_core_auth', '0011_remove_subscription_payment_method'),
    ]

    operations = [
        # Add subscription FK to Invoice
        migrations.AddField(
            model_name='invoice',
            name='subscription',
            field=models.ForeignKey(
                blank=True,
                help_text='Subscription this invoice is for (if subscription-based)',
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name='invoices',
                to='igny8_core_auth.subscription'
            ),
        ),
        # Populate data
        migrations.RunPython(
            populate_subscription_from_metadata,
            reverse_code=migrations.RunPython.noop
        ),
        # Fix Payment status default
        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
            ),
        ),
    ]
