# Generated by Django 4.2.17 on 2024-12-08 13:30
from operator import attrgetter

import django.db.models.deletion
from django.db import migrations, models
from django.db.migrations.state import StateApps
from django.db.models import Count


def delete_duplicates(apps: StateApps, schema_editor):
    """Delete cards of users with more than one student cards.

    For all users who have more than one registered student card, all
    the cards except the last one are deleted.
    """
    Customer = apps.get_model("counter", "Customer")
    StudentCard = apps.get_model("counter", "StudentCard")
    customers = (
        Customer.objects.annotate(nb_cards=Count("student_cards"))
        .filter(nb_cards__gt=1)
        .prefetch_related("student_cards")
    )
    to_delete = [
        card.id
        for customer in customers
        for card in sorted(customer.student_cards.all(), key=attrgetter("id"))[:-1]
    ]
    StudentCard.objects.filter(id__in=to_delete).delete()


class Migration(migrations.Migration):
    dependencies = [("counter", "0025_remove_product_parent_product_and_more")]

    operations = [
        migrations.RunPython(delete_duplicates, migrations.RunPython.noop),
        migrations.AlterField(
            model_name="studentcard",
            name="customer",
            field=models.OneToOneField(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="student_card",
                to="counter.customer",
                verbose_name="student card",
            ),
        ),
        migrations.AlterModelOptions(
            name="studentcard",
            options={
                "verbose_name": "student card",
                "verbose_name_plural": "student cards",
            },
        ),
    ]
