from django.db import migrations, models


def backfill_initial_price(apps, schema_editor):
    PriceWatcher = apps.get_model('pricemon', 'PriceWatcher')
    PriceSnapshot = apps.get_model('pricemon', 'PriceSnapshot')

    for watcher in PriceWatcher.objects.all():
        if watcher.initial_price is not None:
            continue

        snapshot = (
            PriceSnapshot.objects.filter(watcher_id=watcher.pk, price__isnull=False)
            .order_by('checked_at', 'pk')
            .first()
        )
        if snapshot is None:
            continue

        watcher.initial_price = snapshot.price
        watcher.save(update_fields=['initial_price'])


def noop_reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('pricemon', '0004_alert_price_threshold_recurring'),
    ]

    operations = [
        migrations.AddField(
            model_name='pricewatcher',
            name='initial_price',
            field=models.DecimalField(blank=True, decimal_places=2, max_digits=12, null=True),
        ),
        migrations.RunPython(backfill_initial_price, noop_reverse),
    ]
