# Generated by Django 4.1.13 on 2024-03-26 07:31
import json

from django.db import migrations
from django.db.models import F


def migrate_feishu_to_lark(apps, schema_editor):
    setting_model = apps.get_model("settings", "Setting")
    user_model = apps.get_model("users", "User")
    db_alias = schema_editor.connection.alias

    feishu_version_instance = setting_model.objects.using(db_alias).filter(name='FEISHU_VERSION').first()
    if not feishu_version_instance or json.loads(feishu_version_instance.value) == 'feishu':
        return
    feishu_version_instance.delete()

    user_model.objects.using(db_alias).filter(feishu_id__isnull=False).update(lark_id=F('feishu_id'))
    user_model.objects.filter(feishu_id__isnull=False).update(lark_id=F('feishu_id'))
    user_model.objects.filter(feishu_id__isnull=False).update(feishu_id=None)

    settings_to_update = [
        ('AUTH_FEISHU', 'AUTH_LARK'),
        ('FEISHU_APP_ID', 'LARK_APP_ID'),
        ('FEISHU_APP_SECRET', 'LARK_APP_SECRET'),
    ]

    for old_name, new_name in settings_to_update:
        setting_model.objects.using(db_alias).filter(
            name=old_name
        ).update(name=new_name)


class Migration(migrations.Migration):
    dependencies = [
        ('settings', '0012_alter_setting_options'),
        ('users', '0050_user_lark_id_alter_user_source'),
    ]

    operations = [
        migrations.RunPython(migrate_feishu_to_lark),
    ]
