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


def link_latest_weather_forecast(apps, schema_editor):
    SensorData = apps.get_model("sensor_data", "SensorData")
    WeatherForecast = apps.get_model("weather", "WeatherForecast")

    for farm_data in SensorData.objects.all().iterator():
        forecast = (
            WeatherForecast.objects.filter(location_id=farm_data.center_location_id)
            .order_by("-forecast_date", "-id")
            .first()
        )
        if forecast:
            farm_data.weather_forecast_id = forecast.id
            farm_data.save(update_fields=["weather_forecast"])


class Migration(migrations.Migration):

    dependencies = [
        ("sensor_data", "0008_rename_location_to_center_location"),
        ("weather", "0003_seed_weather_forecasts"),
    ]

    operations = [
        migrations.AddField(
            model_name="sensordata",
            name="weather_forecast",
            field=models.ForeignKey(
                blank=True,
                db_column="weather_forecast_id",
                help_text="رکورد آب وهوای مرتبط با مرکز زمین",
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="farm_data_entries",
                to="weather.weatherforecast",
            ),
        ),
        migrations.RunPython(
            link_latest_weather_forecast,
            migrations.RunPython.noop,
        ),
    ]
