# Generated by Django 4.2.9 on 2026-02-28

import re

from django.db import migrations


PATTERN = re.compile(r"^S-(?P<num>\d{3})$")


def forwards(apps, schema_editor):
    EmploymentRecord = apps.get_model("app", "EmploymentRecord")

    used_codes = set()
    keep_ids = set()
    max_seq = 0

    all_rows = EmploymentRecord.objects.order_by("id")
    for row in all_rows:
        code = (row.staff_id_code or "").strip().upper()
        match = PATTERN.match(code)
        if not match:
            continue
        if code in used_codes:
            continue
        used_codes.add(code)
        keep_ids.add(row.pk)
        max_seq = max(max_seq, int(match.group("num")))

    for row in all_rows:
        code = (row.staff_id_code or "").strip().upper()
        match = PATTERN.match(code)
        if match and row.pk in keep_ids:
            continue

        next_seq = max_seq + 1
        while next_seq <= 999:
            candidate = f"S-{next_seq:03d}"
            if candidate not in used_codes:
                EmploymentRecord.objects.filter(pk=row.pk).update(staff_id_code=candidate)
                used_codes.add(candidate)
                max_seq = next_seq
                break
            next_seq += 1


def backwards(apps, schema_editor):
    # Keep normalized identifiers as canonical.
    return


class Migration(migrations.Migration):

    dependencies = [
        ("app", "0082_backfill_staff_id_codes"),
    ]

    operations = [
        migrations.RunPython(forwards, backwards),
    ]
