"""Hash MCPToken values at rest.

Renames ``token`` → ``token_hash`` and rewrites any pre-existing plaintext
values into SHA-256 hex digests in-place. Forward-only: hashing is one-way,
so no reverse migration is provided.

Existing tokens issued before this migration keep working only because
``resolve_mcp_user`` hashes the incoming bearer before lookup; the original
plaintext the client holds still hashes to what we just wrote.
"""

import hashlib

from django.db import migrations, models


def hash_existing_tokens(apps, schema_editor):
    MCPToken = apps.get_model("mcp_server", "MCPToken")
    for token in MCPToken.objects.all():
        plaintext = token.token_hash  # post-rename, still holds original plaintext
        token.token_hash = hashlib.sha256(plaintext.encode("utf-8")).hexdigest()
        token.save(update_fields=["token_hash"])


def noop_reverse(apps, schema_editor):
    # Cannot reverse a hash. Leaving as no-op so the schema can be rolled
    # back, but operators must understand any hashed rows are unrecoverable.
    pass


class Migration(migrations.Migration):
    dependencies = [
        ("mcp_server", "0001_initial"),
    ]

    operations = [
        migrations.RenameField(
            model_name="mcptoken",
            old_name="token",
            new_name="token_hash",
        ),
        migrations.RunPython(hash_existing_tokens, noop_reverse),
    ]
