from django.contrib import admin

from .models import MCPToken


@admin.register(MCPToken)
class MCPTokenAdmin(admin.ModelAdmin):
    list_display = [
        "name",
        "user",
        "is_active",
        "masked_token",
        "expires_at",
        "last_used_at",
        "created_at",
    ]
    list_filter = ["is_active"]
    search_fields = ["name", "user__email", "user__username"]
    readonly_fields = ["token_hash", "last_used_at", "created_at", "updated_at"]
    fieldsets = (
        (None, {"fields": ("user", "name", "is_active")}),
        ("Restrictions", {"fields": ("allowed_tools", "expires_at")}),
        (
            "Token (hashed at rest — plaintext is shown only once at creation)",
            {"fields": ("token_hash",)},
        ),
        ("Audit", {"fields": ("last_used_at", "created_at", "updated_at")}),
    )

    @admin.display(description="Token")
    def masked_token(self, obj):
        return obj.get_masked_token()

    def has_add_permission(self, request):
        # Tokens must be created via the dashboard or management command
        # so the plaintext can be surfaced to the user. Adding via admin
        # would persist a hash with no plaintext ever shown.
        return False
