# Generated by Django 5.2.8 on 2025-11-24 14:33

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


def copy_schedule_data_forward(apps, schema_editor):
    Profile = apps.get_model("ocpp", "ChargingProfile")
    Schedule = apps.get_model("ocpp", "ChargingSchedule")
    for profile in Profile.objects.all():
        Schedule.objects.create(
            profile_id=profile.pk,
            start_schedule=getattr(profile, "start_schedule", None),
            duration_seconds=getattr(profile, "duration_seconds", None),
            charging_rate_unit=getattr(profile, "charging_rate_unit", None),
            charging_schedule_periods=getattr(
                profile, "charging_schedule_periods", []
            ),
            min_charging_rate=getattr(profile, "min_charging_rate", None),
        )


def copy_schedule_data_backward(apps, schema_editor):
    Profile = apps.get_model("ocpp", "ChargingProfile")
    Schedule = apps.get_model("ocpp", "ChargingSchedule")
    for profile in Profile.objects.all():
        try:
            schedule = Schedule.objects.get(profile_id=profile.pk)
        except Schedule.DoesNotExist:
            continue
        profile.start_schedule = schedule.start_schedule
        profile.duration_seconds = schedule.duration_seconds
        profile.charging_rate_unit = schedule.charging_rate_unit
        profile.charging_schedule_periods = schedule.charging_schedule_periods
        profile.min_charging_rate = schedule.min_charging_rate
        profile.save(
            update_fields=[
                "start_schedule",
                "duration_seconds",
                "charging_rate_unit",
                "charging_schedule_periods",
                "min_charging_rate",
            ]
        )


class Migration(migrations.Migration):

    dependencies = [
        ("ocpp", "0063_charger_preferred_ocpp_version_and_more"),
    ]

    operations = [
        migrations.CreateModel(
            name="ChargingProfileDispatch",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("message_id", models.CharField(blank=True, default="", max_length=36)),
                ("status", models.CharField(blank=True, default="", max_length=32)),
                (
                    "status_info",
                    models.CharField(blank=True, default="", max_length=255),
                ),
                ("request_payload", models.JSONField(blank=True, default=dict)),
                ("response_payload", models.JSONField(blank=True, default=dict)),
                ("responded_at", models.DateTimeField(blank=True, null=True)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
            ],
            options={
                "verbose_name": "Charging Profile Dispatch",
                "verbose_name_plural": "Charging Profile Dispatches",
                "ordering": ["-created_at"],
            },
        ),
        migrations.CreateModel(
            name="ChargingSchedule",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "start_schedule",
                    models.DateTimeField(
                        blank=True,
                        help_text="Optional schedule start time; defaults to immediate execution.",
                        null=True,
                    ),
                ),
                (
                    "duration_seconds",
                    models.PositiveIntegerField(
                        blank=True, null=True, verbose_name="Duration (seconds)"
                    ),
                ),
                (
                    "charging_rate_unit",
                    models.CharField(
                        choices=[("A", "Amperes"), ("W", "Watts")],
                        max_length=2,
                        verbose_name="Charging Rate Unit",
                    ),
                ),
                (
                    "charging_schedule_periods",
                    models.JSONField(
                        blank=True,
                        default=list,
                        help_text="List of schedule periods including start_period, limit, number_phases, and phase_to_use values.",
                    ),
                ),
                (
                    "min_charging_rate",
                    models.DecimalField(
                        blank=True,
                        decimal_places=3,
                        max_digits=10,
                        null=True,
                        verbose_name="Minimum Charging Rate",
                    ),
                ),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
            ],
            options={
                "verbose_name": "Charging Schedule",
                "verbose_name_plural": "Charging Schedules",
                "ordering": ["profile_id"],
            },
        ),
        migrations.RunPython(
            copy_schedule_data_forward,
            reverse_code=copy_schedule_data_backward,
        ),
        migrations.RemoveConstraint(
            model_name="chargingprofile",
            name="unique_charging_profile_per_connector",
        ),
        migrations.RemoveField(
            model_name="chargingprofile",
            name="charging_rate_unit",
        ),
        migrations.RemoveField(
            model_name="chargingprofile",
            name="charging_schedule_periods",
        ),
        migrations.RemoveField(
            model_name="chargingprofile",
            name="duration_seconds",
        ),
        migrations.RemoveField(
            model_name="chargingprofile",
            name="min_charging_rate",
        ),
        migrations.RemoveField(
            model_name="chargingprofile",
            name="start_schedule",
        ),
        migrations.AlterField(
            model_name="chargingprofile",
            name="charger",
            field=models.ForeignKey(
                blank=True,
                help_text="Optional default charger context for the profile.",
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="charging_profiles",
                to="ocpp.charger",
                verbose_name="Charger",
            ),
        ),
        migrations.AddConstraint(
            model_name="chargingprofile",
            constraint=models.UniqueConstraint(
                condition=models.Q(("charger__isnull", False)),
                fields=("charger", "connector_id", "charging_profile_id"),
                name="unique_charging_profile_per_connector",
            ),
        ),
        migrations.AddField(
            model_name="chargingprofiledispatch",
            name="charger",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="charging_profile_dispatches",
                to="ocpp.charger",
            ),
        ),
        migrations.AddField(
            model_name="chargingprofiledispatch",
            name="profile",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="dispatches",
                to="ocpp.chargingprofile",
            ),
        ),
        migrations.AddField(
            model_name="chargingschedule",
            name="profile",
            field=models.OneToOneField(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="schedule",
                to="ocpp.chargingprofile",
            ),
        ),
        migrations.AddConstraint(
            model_name="chargingprofiledispatch",
            constraint=models.UniqueConstraint(
                fields=("profile", "charger", "message_id"),
                name="unique_charging_profile_dispatch_message",
            ),
        ),
    ]
