from django.db import migrations

def map_occupation_choices_to_fk(apps, schema_editor):
    Occupation = apps.get_model('accounts', 'Occupation')

    # The previous migration added Occupation to state only. Ensure the table
    # exists during fresh test DB setup before attempting any data operations.
    table_names = schema_editor.connection.introspection.table_names()
    if Occupation._meta.db_table not in table_names:
        schema_editor.create_model(Occupation)

    mapping = {
        'SELF_EMPLOYED': 'Self Employed',
        'BUSINESS_OWNER': 'Business Owner',
        'GOVT_EMPLOYEE': 'Govt Employee',
        'PRIVATE_EMPLOYEE': 'Private Employee',
        'OTHER': 'Other',
    }
    for code, name in mapping.items():
        occ, _ = Occupation.objects.get_or_create(name=name)
        # Use raw SQL because legacy rows can still store string codes in occupation_id
        # after the schema alteration, which breaks ORM integer coercion.
        schema_editor.execute(
            "UPDATE accounts_user SET occupation_id = %s WHERE occupation_id = %s",
            [occ.id, code],
        )

class Migration(migrations.Migration):
    dependencies = [
        ('accounts', '10000_occupation_alter_user_occupation'),
    ]
    operations = [
        migrations.RunPython(map_occupation_choices_to_fk, reverse_code=migrations.RunPython.noop),
    ]
