# 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


def check_table_exists(cursor, table_name):
    """Vérifie si une table existe"""
    cursor.execute(f"SHOW TABLES LIKE '{table_name}'")
    return cursor.fetchone() is not None


def check_column_exists(cursor, table_name, column_name):
    """Vérifie si une colonne existe dans une table"""
    cursor.execute(f"SHOW COLUMNS FROM {table_name} LIKE '{column_name}'")
    return cursor.fetchone() is not None


def forwards_func(apps, schema_editor):
    """Migration des données"""
    try:
        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:
                if isinstance(lottery.winners_distribution, list):
                    distributions = [str(d) for d in lottery.winners_distribution]
                else:
                    distributions = lottery.winners_distribution.split(",")

                for idx, dist in enumerate(distributions, 1):
                    dist = str(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:
                if isinstance(auto.winners_distribution, list):
                    continue
                else:
                    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}")
    except Exception as e:
        print(f"Erreur dans forwards_func: {e}")


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

        for payment in ProcessedPayment.objects.all():
            tickets = TicketPurchase.objects.filter(payment_id=payment.payment_id)
            if tickets.exists():
                ticket = tickets.first()
                payment.user = ticket.user
                payment.character = ticket.character
                payment.payed_at = getattr(ticket, "created_at", None) or getattr(
                    ticket, "purchase_date", None
                )
                payment.amount = getattr(ticket, "amount", None) or (
                    ticket.price * ticket.quantity
                )
                payment.save()
    except Exception as e:
        print(f"Erreur dans fill_processedpayment_fields: {e}")


def convert_notification_config(apps, schema_editor):
    """Conversion du champ notification_config des WebhookConfiguration"""
    try:
        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", [])

                    webhook.notification_config = events
                    webhook.ping_roles = ping_roles
                    webhook.save()
            except Exception as e:
                print(f"Erreur conversion webhook {webhook.pk}: {e}")
    except Exception as e:
        print(f"Erreur dans convert_notification_config: {e}")


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

        for idx, webhook in enumerate(WebhookConfiguration.objects.filter(name=""), 1):
            webhook.name = f"Webhook Configuration {idx}"
            webhook.save()
    except Exception as e:
        print(f"Erreur dans set_default_webhook_name: {e}")


def set_empty_detail(apps, schema_editor):
    """Remplacer les valeurs NULL par une chaîne vide dans TicketAnomaly.detail"""
    try:
        TicketAnomaly = apps.get_model("fortunaisk", "TicketAnomaly")
        TicketAnomaly.objects.filter(detail__isnull=True).update(detail="")
    except Exception as e:
        print(f"Erreur dans set_empty_detail: {e}")


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

        for webhook in WebhookConfiguration.objects.all():
            roles = webhook.ping_roles
            if isinstance(roles, str):
                try:
                    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()
    except Exception as e:
        print(f"Erreur dans fix_ping_roles: {e}")


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 = [
        # Créer d'abord toutes les tables manquantes
        migrations.CreateModel(
            name='WinnerDistribution',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('lottery_reference', models.CharField(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='Winner 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={
                'default_permissions': (),
            },
        ),
        
        # Ajouter les champs manquants aux tables existantes
        migrations.AddField(
            model_name='processedpayment',
            name='character',
            field=models.ForeignKey(blank=True, 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, 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'), max_digits=25, verbose_name='Amount'),
        ),
        migrations.AddField(
            model_name='processedpayment',
            name='payed_at',
            field=models.DateTimeField(blank=True, null=True, verbose_name='Payed At'),
        ),
        
        # Ajouter les champs pour TicketAnomaly
        migrations.AddField(
            model_name='ticketanomaly',
            name='solved',
            field=models.BooleanField(default=False, verbose_name='Solved'),
        ),
        migrations.AddField(
            model_name='ticketanomaly',
            name='solved_at',
            field=models.DateTimeField(blank=True, null=True, verbose_name='Solved At'),
        ),
        migrations.AddField(
            model_name='ticketanomaly',
            name='solved_by',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='solved_anomalies', to=settings.AUTH_USER_MODEL, verbose_name='Solved By'),
        ),
        migrations.AddField(
            model_name='ticketanomaly',
            name='detail',
            field=models.TextField(blank=True, default='', verbose_name='Detail'),
        ),
        
        # Ajouter les champs pour Winner
        migrations.AddField(
            model_name='winner',
            name='distributed_at',
            field=models.DateTimeField(blank=True, null=True, verbose_name='Distributed At'),
        ),
        migrations.AddField(
            model_name='winner',
            name='distributed_by',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='distributed_prizes', to=settings.AUTH_USER_MODEL, verbose_name='Distributed By'),
        ),
        
        # Ajouter les champs pour WebhookConfiguration
        migrations.AddField(
            model_name='webhookconfiguration',
            name='notification_config',
            field=models.JSONField(blank=True, default=list, 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, to=settings.AUTH_USER_MODEL, verbose_name='Created By'),
        ),
        migrations.AddField(
            model_name='webhookconfiguration',
            name='name',
            field=models.CharField(default='', max_length=100, verbose_name='Name'),
        ),
        migrations.AddField(
            model_name='webhookconfiguration',
            name='ping_roles',
            field=models.JSONField(blank=True, default=list, verbose_name='Ping Roles'),
        ),
        
        # Ajouter les champs tax pour AutoLottery et Lottery
        migrations.AddField(
            model_name='autolottery',
            name='tax',
            field=models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=5, verbose_name='Tax Percentage'),
        ),
        migrations.AddField(
            model_name='autolottery',
            name='tax_amount',
            field=models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=25, verbose_name='Tax Amount'),
        ),
        migrations.AddField(
            model_name='lottery',
            name='tax',
            field=models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=5, verbose_name='Tax Percentage'),
        ),
        migrations.AddField(
            model_name='lottery',
            name='tax_amount',
            field=models.DecimalField(decimal_places=2, default=Decimal('0'), max_digits=25, verbose_name='Tax Amount'),
        ),
        
        # Migrer les données
        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.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,
        ),
        
        # Modifier le champ detail pour être non-null
        migrations.AlterField(
            model_name='ticketanomaly',
            name='detail',
            field=models.TextField(default='', verbose_name='Detail'),
        ),
    ]
