from django.db import migrations, models
import django.db.models.deletion


def forwards_copy_boleta_bodega_to_recepcion(apps, schema_editor):
    Recepcion = apps.get_model("recepciones", "Recepcion")

    to_update = []
    qs = Recepcion.objects.select_related("boleta").filter(bodega_destino__isnull=True)
    for r in qs.iterator():
        boleta = getattr(r, "boleta", None)
        bodega_id = getattr(boleta, "bodega_destino_id", None) if boleta is not None else None
        if bodega_id is not None:
            r.bodega_destino_id = bodega_id
            to_update.append(r)

    if to_update:
        Recepcion.objects.bulk_update(to_update, ["bodega_destino"])


def backwards_copy_recepcion_bodega_to_boleta(apps, schema_editor):
    Recepcion = apps.get_model("recepciones", "Recepcion")
    Boleta = apps.get_model("boletas", "Boleta")

    to_update = []
    qs = Recepcion.objects.select_related("boleta").filter(bodega_destino__isnull=False)
    for r in qs.iterator():
        boleta = getattr(r, "boleta", None)
        if boleta is None:
            continue
        if getattr(boleta, "bodega_destino_id", None) is None:
            boleta.bodega_destino_id = r.bodega_destino_id
            to_update.append(boleta)

    if to_update:
        Boleta.objects.bulk_update(to_update, ["bodega_destino"])


class Migration(migrations.Migration):

    dependencies = [
        ("recepciones", "0005_recepcion_rechazo_calidad"),
        ("boletas", "0008_boleta_variedad"),
        ("catalogos", "0007_oficina_en_zafra_variedad_contrato"),
    ]

    operations = [
        migrations.AddField(
            model_name="recepcion",
            name="bodega_destino",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.PROTECT,
                related_name="recepciones_destino",
                to="catalogos.bodega",
            ),
        ),
        migrations.RunPython(
            forwards_copy_boleta_bodega_to_recepcion,
            backwards_copy_recepcion_bodega_to_boleta,
        ),
    ]
