# Generated by Django 5.0.12 on 2025-02-27 04:32

import authentik.lib.utils.time
from authentik.lib.utils.time import timedelta_from_string
from django.db import migrations, models


def convert_integer_to_string_format(apps, schema_editor):
    db_alias = schema_editor.connection.alias
    EmailStage = apps.get_model("authentik_stages_email", "EmailStage")
    for stage in EmailStage.objects.using(db_alias).all():
        stage.token_expiry = f"minutes={stage.token_expiry}"
        stage.save(using=db_alias)


def convert_string_to_integer_format(apps, schema_editor):
    db_alias = schema_editor.connection.alias
    EmailStage = apps.get_model("authentik_stages_email", "EmailStage")
    for stage in EmailStage.objects.using(db_alias).all():
        # Check if token_expiry is a string
        if isinstance(stage.token_expiry, str):
            try:
                # Use the timedelta_from_string utility to convert to timedelta
                # then convert to minutes by dividing seconds by 60
                td = timedelta_from_string(stage.token_expiry)
                minutes_value = int(td.total_seconds() / 60)
                stage.token_expiry = minutes_value
                stage.save(using=db_alias)
            except ValueError, TypeError:
                # If the string can't be parsed or converted properly, skip
                pass


class Migration(migrations.Migration):

    dependencies = [
        ("authentik_stages_email", "0004_emailstage_activate_user_on_success"),
    ]

    operations = [
        migrations.AlterField(
            model_name="emailstage",
            name="token_expiry",
            field=models.TextField(
                default="minutes=30",
                help_text="Time the token sent is valid (Format: hours=3,minutes=17,seconds=300).",
                validators=[authentik.lib.utils.time.timedelta_string_validator],
            ),
        ),
        migrations.RunPython(
            convert_integer_to_string_format,
            convert_string_to_integer_format,
        ),
    ]
