# Generated by Django 5.2.4 on 2025-09-23 20:53

from django.db import migrations, models

from django.db import migrations
from django.utils import timezone
import random
import string

def _gen_wallet_credit_oid():
    # WCR + yymmdd + 6 digits => 15 chars
    return "WCR" + timezone.now().strftime("%y%m%d") + "".join(random.choices(string.digits, k=6))

def backfill_unique_order_ids(apps, schema_editor):
    Usage = apps.get_model("payments", "ViralPeWalletUsage")

    # Work in PK order so we deterministically fix duplicates
    seen = set()
    qs = Usage.objects.order_by("id")

    # First pass: collect counts for existing non-null, non-empty order_ids
    from collections import Counter
    vals = list(qs.values_list("order_id", flat=True))
    counts = Counter(v for v in vals if v)  # ignore None / empty
    duplicates = {v for v, c in counts.items() if c > 1}

    for row in qs:
        oid = (row.order_id or "").strip()

        needs_new = False
        if not oid:             # None or ""
            needs_new = True
        elif oid in seen:       # already used in this loop
            needs_new = True
        elif oid in duplicates: # appears more than once in DB
            needs_new = True

        if needs_new:
            # generate a unique one that doesn't collide
            new_oid = _gen_wallet_credit_oid()
            while (new_oid in seen) or Usage.objects.filter(order_id=new_oid).exists():
                new_oid = _gen_wallet_credit_oid()

            row.order_id = new_oid
            row.save(update_fields=["order_id"])
            seen.add(new_oid)
        else:
            seen.add(oid)



class Migration(migrations.Migration):

    dependencies = [
        ('payments', '0016_paymenttransaction_metadata_and_more'),
    ]

    operations = [
        migrations.AddField(
            model_name='viralpewalletusage',
            name='purpose_code',
            field=models.CharField(choices=[('manual_test', 'Manual Top-Up (Testing)'), ('manual_admin', 'Manual Top-Up (Admin)'), ('oneapp_withdrawal', 'Credit from 1App Withdrawal'), ('other', 'Other')], default='manual_admin', max_length=32),
        ),
        migrations.AddField(
            model_name='viralpewalletusage',
            name='purpose_note',
            field=models.CharField(blank=True, default='', max_length=200),
        ),

        migrations.RunPython(backfill_unique_order_ids),
        migrations.AlterField(
            model_name='viralpewalletusage',
            name='order_id',
            field=models.CharField(blank=True, db_index=True, max_length=32, null=True, unique=True),
        ),
        migrations.AlterField(
            model_name='viralpewalletusage',
            name='transaction_type',
            field=models.CharField(choices=[('credit', 'Credit'), ('debit', 'Debit')], default='credit', max_length=10),
        ),
    ]
