"""club 表增加 mch_key 列（APIv2 小程序支付密钥），从 config_json 迁移历史数据。"""
from django.db import migrations, models


def copy_mch_key_from_config_json(apps, schema_editor):
    Club = apps.get_model('jituan', 'Club')
    for club in Club.objects.all():
        cfg = club.config_json or {}
        legacy = (cfg.get('mch_key') or cfg.get('shanghumiyao') or '').strip()
        if legacy and not (club.mch_key or '').strip():
            club.mch_key = legacy
            club.save(update_fields=['mch_key'])


class Migration(migrations.Migration):

    dependencies = [
        ('jituan', '0011_club_payment_channel'),
    ]

    operations = [
        migrations.AddField(
            model_name='club',
            name='mch_key',
            field=models.CharField(
                blank=True,
                default='',
                max_length=128,
                verbose_name='APIv2商户密钥',
            ),
        ),
        migrations.RunPython(copy_mch_key_from_config_json, migrations.RunPython.noop),
    ]
