# Data migration: populate new billing fields from existing seconds-based data
from django.db import migrations


def forward(apps, schema_editor):
    Team = apps.get_model('accounts', 'Team')
    User = apps.get_model('accounts', 'User')
    QuotaConfig = apps.get_model('generation', 'QuotaConfig')

    # Teams: set balance=0 (admin will manually top up), spending limit=-1 (unlimited)
    for team in Team.objects.all():
        team.balance = 0
        team.total_spent = 0
        team.monthly_spending_limit = -1
        team.daily_member_spending_default = 50
        team.frozen_amount = 0
        team.markup_percentage = 0
        team.save(update_fields=[
            'balance', 'total_spent', 'monthly_spending_limit',
            'daily_member_spending_default', 'frozen_amount', 'markup_percentage',
        ])

    # Users: set generation limits
    User.objects.all().update(
        daily_generation_limit=50,
        monthly_generation_limit=1500,
    )

    # QuotaConfig: set defaults
    config, _ = QuotaConfig.objects.get_or_create(pk=1)
    config.default_daily_generation_limit = 50
    config.default_monthly_generation_limit = 1500
    config.base_token_price = 46
    config.save(update_fields=[
        'default_daily_generation_limit', 'default_monthly_generation_limit', 'base_token_price',
    ])


def backward(apps, schema_editor):
    pass  # No rollback needed, old seconds fields are untouched


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0009_billing_system_v010'),
        ('generation', '0007_billing_system_v010'),
    ]

    operations = [
        migrations.RunPython(forward, backward),
    ]
