# Generated migration to add Payment FK to CreditTransaction

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


class Migration(migrations.Migration):

    dependencies = [
        ('billing', '0011_add_manual_reference_constraint'),
    ]

    operations = [
        # Add payment FK field
        migrations.AddField(
            model_name='credittransaction',
            name='payment',
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name='credit_transactions',
                to='billing.payment',
                help_text='Payment that triggered this credit transaction'
            ),
        ),
        
        # Migrate existing reference_id data to payment FK
        migrations.RunSQL(
            sql="""
            UPDATE igny8_credit_transactions ct
            SET payment_id = (
                SELECT id FROM igny8_payments p 
                WHERE p.id::text = ct.reference_id 
                AND ct.reference_id ~ '^[0-9]+$'
                LIMIT 1
            )
            WHERE ct.reference_id IS NOT NULL 
            AND ct.reference_id != ''
            AND ct.reference_id ~ '^[0-9]+$';
            """,
            reverse_sql=migrations.RunSQL.noop
        ),
    ]
