from django.contrib import admin
from rest_framework_api_key.admin import APIKeyModelAdmin
from rest_framework_api_key.models import APIKey as DefaultAPIKey
from .models import APIKey

# Unregister the default APIKey admin
admin.site.unregister(DefaultAPIKey)


@admin.register(APIKey)
class APIKeyAdmin(APIKeyModelAdmin):
    list_display = [*APIKeyModelAdmin.list_display, "user"]
    list_filter = [*APIKeyModelAdmin.list_filter, "user"]
    search_fields = [*APIKeyModelAdmin.search_fields, "user__username", "user__email"]
    raw_id_fields = ['user']

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        # Make user field required
        if 'user' in form.base_fields:
            form.base_fields['user'].required = True
        return form
