# Generated by Django 5.2.4 on 2025-09-20 23:45

from django.db import migrations, models


def collapse_monthly_tariffs(apps, schema_editor):
    """Remove duplicate tariff rows created when dropping the month column."""

    EnergyTariff = apps.get_model("core", "EnergyTariff")
    connection = schema_editor.connection
    table = EnergyTariff._meta.db_table
    pk_column = EnergyTariff._meta.pk.column
    quoted_table = connection.ops.quote_name(table)
    quoted_pk = connection.ops.quote_name(pk_column)
    partition_fields = [
        "year",
        "season",
        "zone",
        "contract_type",
        "period",
        "unit",
        "start_time",
        "end_time",
    ]
    partition_columns = ", ".join(
        connection.ops.quote_name(field) for field in partition_fields
    )
    order_expression = ", ".join(
        [
            f"{connection.ops.quote_name('is_deleted')} ASC",
            f"{quoted_pk} ASC",
        ]
    )

    if getattr(connection.features, "supports_over_clause", False):
        sql = f"""
            DELETE FROM {quoted_table}
            WHERE {quoted_pk} IN (
                SELECT {quoted_pk}
                FROM (
                    SELECT
                        {quoted_pk},
                        ROW_NUMBER() OVER (
                            PARTITION BY {partition_columns}
                            ORDER BY {order_expression}
                        ) AS rn
                    FROM {quoted_table}
                ) AS ranked
                WHERE rn > 1
            )
        """
        with connection.cursor() as cursor:
            cursor.execute(sql)
        return

    manager = getattr(EnergyTariff, "all_objects", EnergyTariff._default_manager)
    seen: dict[tuple, object] = {}
    removals: set[int] = set()
    order_by_fields = partition_fields + ["is_deleted", EnergyTariff._meta.pk.name]

    for tariff in manager.all().order_by(*order_by_fields):
        key = tuple(getattr(tariff, field) for field in partition_fields)
        keep = seen.get(key)
        if keep is None:
            seen[key] = tariff
            continue

        keep_deleted = getattr(keep, "is_deleted", False)
        current_deleted = getattr(tariff, "is_deleted", False)

        if keep_deleted and not current_deleted:
            removals.add(keep.pk)
            seen[key] = tariff
        else:
            removals.add(tariff.pk)

    if removals:
        placeholders = ", ".join(["%s"] * len(removals))
        sql = (
            f"DELETE FROM {quoted_table} "
            f"WHERE {quoted_pk} IN ({placeholders})"
        )
        with connection.cursor() as cursor:
            cursor.execute(sql, sorted(removals))


class Migration(migrations.Migration):

    dependencies = [
        ("core", "0038_energytariff"),
    ]

    operations = [
        migrations.RemoveConstraint(
            model_name="energytariff",
            name="uniq_energy_tariff_schedule",
        ),
        migrations.RemoveIndex(
            model_name="energytariff",
            name="energy_tariff_schedule_idx",
        ),
        migrations.RenameField(
            model_name="energytariff",
            old_name="time_of_day",
            new_name="period",
        ),
        migrations.RemoveField(
            model_name="energytariff",
            name="month",
        ),
        migrations.AddField(
            model_name="energytariff",
            name="season",
            field=models.CharField(
                choices=[
                    ("annual", "All year"),
                    ("summer", "Summer season"),
                    ("non_summer", "Non-summer season"),
                ],
                default="annual",
                help_text="Season or applicability window defined by CFE.",
                max_length=16,
            ),
        ),
        migrations.AddField(
            model_name="energytariff",
            name="unit",
            field=models.CharField(
                choices=[
                    ("kwh", "Kilowatt-hour"),
                    ("kw", "Kilowatt"),
                    ("month", "Monthly charge"),
                ],
                default="kwh",
                help_text="Measurement unit for the tariff charge.",
                max_length=16,
            ),
        ),
        migrations.AddField(
            model_name="energytariff",
            name="notes",
            field=models.TextField(
                default="",
                help_text="Context or special billing conditions published by CFE.",
                blank=True,
            ),
        ),
        migrations.AlterField(
            model_name="energytariff",
            name="contract_type",
            field=models.CharField(
                choices=[
                    ("domestic", "Domestic service (Tarifa 1)"),
                    ("dac", "High consumption domestic (DAC)"),
                    ("pdbt", "General service low demand (PDBT)"),
                    ("gdbt", "General service high demand (GDBT)"),
                    ("gdmto", "General distribution medium tension (GDMTO)"),
                    (
                        "gdmth",
                        "General distribution medium tension hourly (GDMTH)",
                    ),
                ],
                help_text="Type of service contract regulated by CFE.",
                max_length=16,
            ),
        ),
        migrations.AlterField(
            model_name="energytariff",
            name="period",
            field=models.CharField(
                choices=[
                    ("flat", "Flat rate"),
                    ("basic", "Basic block"),
                    ("intermediate_1", "Intermediate block 1"),
                    ("intermediate_2", "Intermediate block 2"),
                    ("excess", "Excess consumption"),
                    ("base", "Base"),
                    ("intermediate", "Intermediate"),
                    ("peak", "Peak"),
                    ("critical_peak", "Critical peak"),
                    ("demand", "Demand charge"),
                    ("capacity", "Capacity charge"),
                    ("distribution", "Distribution charge"),
                    ("fixed", "Fixed charge"),
                ],
                help_text="Tariff block, demand component, or time-of-use period.",
                max_length=32,
            ),
        ),
        migrations.AlterField(
            model_name="energytariff",
            name="price_mxn",
            field=models.DecimalField(
                decimal_places=4,
                help_text="Customer price per unit in MXN.",
                max_digits=10,
            ),
        ),
        migrations.AlterField(
            model_name="energytariff",
            name="cost_mxn",
            field=models.DecimalField(
                decimal_places=4,
                help_text="Provider cost per unit in MXN.",
                max_digits=10,
            ),
        ),
        migrations.AddIndex(
            model_name="energytariff",
            index=models.Index(
                fields=["year", "season", "zone", "contract_type"],
                name="energy_tariff_scope_idx",
            ),
        ),
        migrations.RunPython(
            collapse_monthly_tariffs, migrations.RunPython.noop
        ),
        migrations.AddConstraint(
            model_name="energytariff",
            constraint=models.UniqueConstraint(
                fields=[
                    "year",
                    "season",
                    "zone",
                    "contract_type",
                    "period",
                    "unit",
                    "start_time",
                    "end_time",
                ],
                name="uniq_energy_tariff_schedule",
            ),
        ),
    ]
