# fortunaisk/migrations/0007_add_new_schema_squashed_0020_alter_ticketanomaly_detail.py
# Generated by Django 4.2.20 on 2025-05-30 13:34

# Standard Library
from decimal import Decimal

# Django
import django.db.migrations.operations.special
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models


# Fonctions migrées des migrations d'origine
def forwards_func(apps, schema_editor):
    """
    Migration 0008: Transfert des données des anciens modèles vers les nouveaux.
    """
    # Récupérer les modèles
    AutoLottery = apps.get_model("fortunaisk", "AutoLottery")
    Lottery = apps.get_model("fortunaisk", "Lottery")
    WinnerDistribution = apps.get_model("fortunaisk", "WinnerDistribution")

    # Migrer les distributions de gagnants
    for lottery in Lottery.objects.all():
        if not lottery.winners_distribution:
            continue

        try:
            distributions = lottery.winners_distribution.split(",")
            for idx, dist in enumerate(distributions, 1):
                dist = dist.strip()
                if not dist:
                    continue

                WinnerDistribution.objects.create(
                    lottery_reference=lottery.lottery_reference,
                    winner_rank=idx,
                    winner_prize_distribution=Decimal(dist.strip("%")),
                )
        except Exception as e:
            print(f"Erreur migration lottery {lottery.pk}: {e}")

    # Migrer les distributions d'auto-loteries
    for auto in AutoLottery.objects.all():
        if not auto.winners_distribution:
            continue

        try:
            # Convertir en liste JSON
            distributions = auto.winners_distribution.split(",")
            auto.winners_distribution = [
                float(d.strip("%")) for d in distributions if d.strip()
            ]
            auto.save()
        except Exception as e:
            print(f"Erreur migration autolottery {auto.pk}: {e}")


def fill_processedpayment_fields(apps, schema_editor):
    """
    Migration 0009: Remplissage des champs user/character dans ProcessedPayment.
    """
    ProcessedPayment = apps.get_model("fortunaisk", "ProcessedPayment")
    TicketPurchase = apps.get_model("fortunaisk", "TicketPurchase")

    # Mettre à jour les paiements traités avec les utilisateurs et personnages correspondants
    for payment in ProcessedPayment.objects.all():
        tickets = TicketPurchase.objects.filter(payment_ref=payment.payment_ref)
        if tickets.exists():
            ticket = tickets.first()
            payment.user = ticket.user
            payment.character = ticket.character
            payment.payed_at = ticket.created_at
            payment.amount = ticket.price * ticket.quantity
            payment.save()


def convert_notification_config(apps, schema_editor):
    """
    Migration 0016: Conversion du champ notification_config des WebhookConfiguration
    """
    WebhookConfiguration = apps.get_model("fortunaisk", "WebhookConfiguration")

    for webhook in WebhookConfiguration.objects.all():
        try:
            config = webhook.notification_config
            if isinstance(config, dict):
                events = config.get("events", [])
                ping_roles = config.get("ping_roles", [])

                # Mettre à jour avec la nouvelle structure
                webhook.notification_config = events
                webhook.ping_roles = ping_roles
                webhook.save()
        except Exception as e:
            print(f"Erreur conversion webhook {webhook.pk}: {e}")


def set_default_webhook_name(apps, schema_editor):
    """
    Migration 0017: Définir des noms par défaut pour les webhooks
    """
    WebhookConfiguration = apps.get_model("fortunaisk", "WebhookConfiguration")

    for idx, webhook in enumerate(WebhookConfiguration.objects.filter(name=""), 1):
        webhook.name = f"Webhook Configuration {idx}"
        webhook.save()


def set_empty_detail(apps, schema_editor):
    """
    Migration 0018: Remplacer les valeurs NULL par une chaîne vide dans TicketAnomaly.detail
    """
    TicketAnomaly = apps.get_model("fortunaisk", "TicketAnomaly")

    TicketAnomaly.objects.filter(detail__isnull=True).update(detail="")


def fix_ping_roles(apps, schema_editor):
    """
    Migration 0019: Corriger le format des ping_roles dans WebhookConfiguration
    """
    WebhookConfiguration = apps.get_model("fortunaisk", "WebhookConfiguration")

    for webhook in WebhookConfiguration.objects.all():
        roles = webhook.ping_roles
        if isinstance(roles, str):
            try:
                # Tenter de convertir une chaîne en liste
                webhook.ping_roles = [
                    role.strip() for role in roles.split(",") if role.strip()
                ]
                webhook.save()
            except Exception as e:
                print(f"Erreur correction ping_roles {webhook.pk}: {e}")
                webhook.ping_roles = []
                webhook.save()


class Migration(migrations.Migration):

    replaces = [
        ("fortunaisk", "0007_add_new_schema"),
        ("fortunaisk", "0008_migrate_data"),
        ("fortunaisk", "0009_fill_processedpayment_fields"),
        ("fortunaisk", "0010_autolottery_tax_lottery_tax"),
        ("fortunaisk", "0011_autolottery_tax_amount_lottery_tax_amount"),
        ("fortunaisk", "0012_alter_autolottery_winners_distribution_and_more"),
        ("fortunaisk", "0013_remove_lottery_winners_distribution"),
        ("fortunaisk", "0014_alter_webhookconfiguration_options_and_more"),
        ("fortunaisk", "0015_alter_webhookconfiguration_options_and_more"),
        ("fortunaisk", "0016_convert_notification_config"),
        ("fortunaisk", "0017_fill_webhook_names"),
        ("fortunaisk", "0018_fill_detail_empty"),
        ("fortunaisk", "0019_fix_ping_roles"),
        ("fortunaisk", "0020_alter_ticketanomaly_detail"),
    ]

    dependencies = [
        ("eveonline", "0017_alliance_and_corp_names_are_not_unique"),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ("fortunaisk", "0006_lowercase_interval_period"),
    ]

    operations = [
        migrations.CreateModel(
            name="WinnerDistribution",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "lottery_reference",
                    models.CharField(
                        db_index=True, max_length=20, verbose_name="Lottery Reference"
                    ),
                ),
                (
                    "winner_rank",
                    models.PositiveIntegerField(verbose_name="Winner Rank"),
                ),
                (
                    "winner_prize_distribution",
                    models.DecimalField(
                        decimal_places=2,
                        max_digits=5,
                        verbose_name="Prize Distribution (%)",
                    ),
                ),
                (
                    "created_at",
                    models.DateTimeField(auto_now_add=True, verbose_name="Created At"),
                ),
                (
                    "updated_at",
                    models.DateTimeField(auto_now=True, verbose_name="Updated At"),
                ),
            ],
            options={
                "db_table": "fortunaisk_winner_distribution",
                "ordering": ["lottery_reference", "winner_rank"],
            },
        ),
        migrations.AddField(
            model_name="processedpayment",
            name="character",
            field=models.ForeignKey(
                blank=True,
                help_text="EVE character (if identified).",
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eveonline.evecharacter",
                verbose_name="Eve Character",
            ),
        ),
        migrations.AddField(
            model_name="processedpayment",
            name="user",
            field=models.ForeignKey(
                blank=True,
                help_text="Django user (if identified).",
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to=settings.AUTH_USER_MODEL,
                verbose_name="Django User",
            ),
        ),
        migrations.AddField(
            model_name="processedpayment",
            name="amount",
            field=models.DecimalField(
                decimal_places=2,
                default=Decimal("0.00"),
                help_text="Total amount paid in ISK.",
                max_digits=25,
                verbose_name="Total Paid Amount",
            ),
        ),
        migrations.AddField(
            model_name="processedpayment",
            name="payed_at",
            field=models.DateTimeField(
                blank=True,
                help_text="Payment date & time.",
                null=True,
                verbose_name="Paid At",
            ),
        ),
        migrations.AddField(
            model_name="ticketanomaly",
            name="solved",
            field=models.BooleanField(
                default=False,
                help_text="Anomaly marked as solved.",
                verbose_name="Solved",
            ),
        ),
        migrations.AddField(
            model_name="ticketanomaly",
            name="solved_at",
            field=models.DateTimeField(
                blank=True,
                help_text="Resolution date & time.",
                null=True,
                verbose_name="Solved At",
            ),
        ),
        migrations.AddField(
            model_name="ticketanomaly",
            name="solved_by",
            field=models.ForeignKey(
                blank=True,
                help_text="User who resolved the anomaly.",
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="resolved_anomalies",
                to=settings.AUTH_USER_MODEL,
                verbose_name="Solved By",
            ),
        ),
        migrations.AddField(
            model_name="ticketanomaly",
            name="detail",
            field=models.TextField(
                blank=True,
                help_text="Resolution details.",
                null=True,
                verbose_name="Resolution Detail",
            ),
        ),
        migrations.AddField(
            model_name="winner",
            name="distributed_at",
            field=models.DateTimeField(
                blank=True,
                help_text="Prize distribution date & time.",
                null=True,
                verbose_name="Distributed At",
            ),
        ),
        migrations.AddField(
            model_name="winner",
            name="distributed_by",
            field=models.ForeignKey(
                blank=True,
                help_text="User who distributed the prize.",
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="distributed_winnings",
                to=settings.AUTH_USER_MODEL,
                verbose_name="Distributed By",
            ),
        ),
        migrations.AddField(
            model_name="webhookconfiguration",
            name="notification_config",
            field=models.JSONField(
                blank=True,
                default=dict,
                help_text="Notification settings (channels, types, etc).",
                verbose_name="Notification Config",
            ),
        ),
        migrations.AddField(
            model_name="webhookconfiguration",
            name="created_at",
            field=models.DateTimeField(
                auto_now_add=True,
                default=django.utils.timezone.now,
                verbose_name="Created At",
            ),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name="webhookconfiguration",
            name="created_by",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="webhook_configurations",
                to=settings.AUTH_USER_MODEL,
                verbose_name="Created By",
            ),
        ),
        migrations.RunPython(
            code=forwards_func,
            reverse_code=django.db.migrations.operations.special.RunPython.noop,
        ),
        migrations.RunPython(
            code=fill_processedpayment_fields,
            reverse_code=django.db.migrations.operations.special.RunPython.noop,
        ),
        migrations.AddField(
            model_name="autolottery",
            name="tax",
            field=models.DecimalField(
                decimal_places=2,
                default=Decimal("0.00"),
                help_text="Percentage of tax applied to the total pot before distribution.",
                max_digits=5,
                verbose_name="Tax (%)",
            ),
        ),
        migrations.AddField(
            model_name="autolottery",
            name="tax_amount",
            field=models.DecimalField(
                decimal_places=2,
                default=Decimal("0.00"),
                help_text="Amount of tax (in ISK) computed from the gross pot.",
                max_digits=25,
                verbose_name="Tax Amount (ISK)",
            ),
        ),
        migrations.AddField(
            model_name="lottery",
            name="tax_amount",
            field=models.DecimalField(
                decimal_places=2,
                default=Decimal("0.00"),
                help_text="Amount of tax (in ISK) computed from the gross pot.",
                max_digits=25,
                verbose_name="Tax Amount (ISK)",
            ),
        ),
        migrations.AlterField(
            model_name="autolottery",
            name="winners_distribution",
            field=models.JSONField(
                blank=True,
                default=list,
                help_text="List of percentage distributions for winners (sum must be 100).",
                verbose_name="Winners Distribution",
            ),
        ),
        migrations.AddField(
            model_name="lottery",
            name="tax",
            field=models.DecimalField(
                decimal_places=2,
                default=Decimal("0.00"),
                help_text="Percentage of tax applied to the gross pot before distribution.",
                max_digits=5,
                verbose_name="Tax (%)",
            ),
        ),
        migrations.AlterField(
            model_name="lottery",
            name="total_pot",
            field=models.DecimalField(
                decimal_places=2,
                default=Decimal("0.00"),
                help_text="Total ISK pot from ticket purchases after tax.",
                max_digits=25,
                verbose_name="Total Pot (ISK)",
            ),
        ),
        migrations.RemoveField(
            model_name="lottery",
            name="winners_distribution",
        ),
        migrations.AlterModelOptions(
            name="webhookconfiguration",
            options={
                "default_permissions": (),
                "verbose_name": "Webhook Configuration",
            },
        ),
        migrations.AlterField(
            model_name="lottery",
            name="payment_receiver",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="lotteries",
                to="eveonline.evecorporationinfo",
                verbose_name="Payment Receiver",
            ),
        ),
        migrations.AlterField(
            model_name="webhookconfiguration",
            name="created_by",
            field=models.ForeignKey(
                blank=True,
                help_text="User who created this configuration.",
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="webhook_configurations",
                to=settings.AUTH_USER_MODEL,
                verbose_name="Created By",
            ),
        ),
        migrations.AlterField(
            model_name="webhookconfiguration",
            name="notification_config",
            field=models.JSONField(
                blank=True,
                default=dict,
                help_text='JSON object with two keys:\n  • "events": list of event names to send publicly\n  • "ping_roles": list of Discord role IDs to mention on each notification\nExample:\n{\n  "events": [\n    "lottery_created",\n    "lottery_sales_closed",\n    "anomaly_detected"\n  ],\n  "ping_roles": ["123456789012345678", "987654321098765432"]\n}',
                verbose_name="Notification Configuration",
            ),
        ),
        migrations.AlterField(
            model_name="webhookconfiguration",
            name="webhook_url",
            field=models.URLField(
                blank=True,
                help_text="URL of the Discord webhook to send public notifications. Leave blank to disable.",
                null=True,
                verbose_name="Discord Webhook URL",
            ),
        ),
        migrations.AlterModelOptions(
            name="webhookconfiguration",
            options={"default_permissions": ()},
        ),
        migrations.AddField(
            model_name="webhookconfiguration",
            name="name",
            field=models.CharField(
                blank=True,
                default="",
                help_text="A unique name for this webhook configuration.",
                max_length=100,
                unique=True,
                verbose_name="Configuration Name",
            ),
        ),
        migrations.AddField(
            model_name="webhookconfiguration",
            name="ping_roles",
            field=models.JSONField(
                blank=True,
                default=list,
                help_text="List of Discord role IDs to mention when sending.",
                verbose_name="Ping Roles",
            ),
        ),
        migrations.AlterField(
            model_name="webhookconfiguration",
            name="created_by",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="webhook_configurations",
                to=settings.AUTH_USER_MODEL,
                verbose_name="Created By",
            ),
        ),
        migrations.AlterField(
            model_name="webhookconfiguration",
            name="notification_config",
            field=models.JSONField(
                blank=True,
                default=list,
                help_text="Which events (by key) should be sent to this webhook.",
                verbose_name="Events to Notify",
            ),
        ),
        migrations.AlterField(
            model_name="webhookconfiguration",
            name="webhook_url",
            field=models.URLField(
                blank=True,
                help_text="The URL to post embeds and messages to.",
                null=True,
                verbose_name="Discord Webhook URL",
            ),
        ),
        migrations.RunPython(
            code=convert_notification_config,
            reverse_code=django.db.migrations.operations.special.RunPython.noop,
        ),
        migrations.RunPython(
            code=set_default_webhook_name,
            reverse_code=django.db.migrations.operations.special.RunPython.noop,
        ),
        migrations.RunPython(
            code=set_empty_detail,
            reverse_code=django.db.migrations.operations.special.RunPython.noop,
        ),
        migrations.RunPython(
            code=fix_ping_roles,
            reverse_code=django.db.migrations.operations.special.RunPython.noop,
        ),
        migrations.AlterField(
            model_name="ticketanomaly",
            name="detail",
            field=models.TextField(
                blank=True,
                default="",
                help_text="Resolution details.",
                null=True,
                verbose_name="Resolution Detail",
            ),
        ),
    ]
