# Generated by Django 4.2.28 on 2026-02-23 15:34

from django.db import migrations


def fill_personenid_and_reuid(_apps, schema_editor):
    # PersonenID and REUID were never added via AddField migration (managed=False table),
    # so the historical ORM model doesn't know these fields. Use raw SQL instead.
    with schema_editor.connection.cursor() as cursor:
        cursor.execute("""
            UPDATE tbl_v_i_sys_ver_rahmen AS r
            INNER JOIN reu_miet_v_s AS m ON r.MietVID = m.MietVID
            SET r.PersonenID_id = m.MieterID,
                r.REUID_id = m.REUID
            WHERE r.MietVID IS NOT NULL
        """)
        updated = cursor.rowcount

    print(f"Migration: {updated} Datensätze aktualisiert")


def reverse_migration(_apps, schema_editor):
    with schema_editor.connection.cursor() as cursor:
        cursor.execute("""
            UPDATE tbl_v_i_sys_ver_rahmen
            SET PersonenID_id = NULL, REUID_id = NULL
        """)


class Migration(migrations.Migration):

    dependencies = [
        ('app_verbrauch', '0002_alter_visysverbrauchart_options'),
    ]

    operations = [
        migrations.RunPython(fill_personenid_and_reuid, reverse_migration),
    ]
