# Generated by Django 5.2 on 2025-09-23 12:50

from django.db import migrations


def populate_from_env(apps, _schema_editor):
    from django.conf import settings
    from api.encryption import SecretsEncryption

    StripeConfig = apps.get_model('api', 'StripeConfig')
    StripeConfigEntry = apps.get_model('api', 'StripeConfigEntry')

    release_env = getattr(settings, 'GOBII_RELEASE_ENV', 'local')
    live_mode = bool(getattr(settings, 'STRIPE_LIVE_MODE', False))

    config, created = StripeConfig.objects.get_or_create(
        release_env=release_env,
        defaults={'live_mode': live_mode},
    )

    if not created and config.live_mode != live_mode:
        config.live_mode = live_mode
        config.save(update_fields=['live_mode'])

    field_map = [
        ('live_secret_key', 'STRIPE_LIVE_SECRET_KEY', True),
        ('test_secret_key', 'STRIPE_TEST_SECRET_KEY', True),
        ('webhook_secret', 'STRIPE_WEBHOOK_SECRET', True),
        ('startup_price_id', 'STRIPE_STARTUP_PRICE_ID', False),
        ('startup_additional_task_price_id', 'STRIPE_STARTUP_ADDITIONAL_TASK_PRICE_ID', False),
        ('startup_product_id', 'STRIPE_STARTUP_PRODUCT_ID', False),
        ('org_team_product_id', 'STRIPE_ORG_TEAM_PRODUCT_ID', False),
        ('org_team_price_id', 'STRIPE_ORG_TEAM_PRICE_ID', False),
        (
            'org_team_additional_task_price_id',
            'STRIPE_ORG_TEAM_ADDITIONAL_TASK_PRICE_ID',
            False,
        ),
        ('org_team_task_meter_id', 'STRIPE_ORG_TEAM_TASK_METER_ID', False),
        (
            'org_team_task_meter_event_name',
            'STRIPE_ORG_TEAM_TASK_METER_EVENT_NAME',
            False,
        ),
        ('task_meter_id', 'STRIPE_TASK_METER_ID', False),
        ('task_meter_event_name', 'STRIPE_TASK_METER_EVENT_NAME', False),
        ('org_task_meter_id', 'STRIPE_ORG_TASK_METER_ID', False),
    ]

    for entry_name, setting_name, is_secret in field_map:
        raw_value = getattr(settings, setting_name, None)
        if raw_value in (None, ''):
            continue

        defaults = {'is_secret': is_secret}
        if is_secret:
            defaults['value_encrypted'] = SecretsEncryption.encrypt_value(raw_value)
            defaults['value_text'] = ''
        else:
            defaults['value_text'] = str(raw_value)
            defaults['value_encrypted'] = None

        entry, entry_created = StripeConfigEntry.objects.get_or_create(
            config=config,
            name=entry_name,
            defaults=defaults,
        )

        if entry_created:
            continue

        updated = False
        if entry.is_secret != is_secret:
            entry.is_secret = is_secret
            updated = True

        if is_secret:
            new_encrypted = SecretsEncryption.encrypt_value(raw_value)
            if entry.value_encrypted != new_encrypted or entry.value_text:
                entry.value_encrypted = new_encrypted
                entry.value_text = ''
                updated = True
        else:
            new_text = str(raw_value)
            if entry.value_text != new_text or entry.value_encrypted is not None:
                entry.value_text = new_text
                entry.value_encrypted = None
                updated = True

        if updated:
            entry.save(update_fields=['value_text', 'value_encrypted', 'is_secret', 'updated_at'])


def noop(*_args, **_kwargs):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('api', '0140_stripeconfig_stripeconfigentry'),
    ]

    operations = [
        migrations.RunPython(populate_from_env, noop),
    ]
