from django.contrib import admin
from org_authz.models import Organization, Role, Permission, RolePermission, UserRole
from django.contrib.auth import get_user_model

User = get_user_model()


class RolePermissionInline(admin.TabularInline):
    """Inline for linking roles and permissions."""
    model = RolePermission
    extra = 1
    autocomplete_fields = ("permission",)


class RoleInline(admin.TabularInline):
    """Inline for roles under an Organization."""
    model = Role
    extra = 1
    fields = ("name", "description")
    show_change_link = True


class UserRoleInline(admin.TabularInline):
    """Inline for assigning users to roles within an Organization."""
    model = UserRole
    extra = 1
    fields = ("user", "role")
    autocomplete_fields = ("user", "role")


@admin.register(Organization)
class OrganizationAdmin(admin.ModelAdmin):
    """Admin page for managing organizations, their roles, and users."""
    list_display = ("name", "slug", "created_at")
    search_fields = ("name", "slug")
    inlines = [RoleInline, UserRoleInline]

    fieldsets = (
        (None, {
            "fields": ("name", "slug")
        }),
    )


@admin.register(Role)
class RoleAdmin(admin.ModelAdmin):
    """Admin page for roles, showing related permissions."""
    list_display = ("name", "organization")
    list_filter = ("organization",)
    search_fields = ("name",)
    inlines = [RolePermissionInline]

    fieldsets = (
        (None, {
            "fields": ("organization", "name", "description")
        }),
    )


@admin.register(Permission)
class PermissionAdmin(admin.ModelAdmin):
    """Manage permissions."""
    list_display = ("name", "code")
    search_fields = ("name", "code")


@admin.register(UserRole)
class UserRoleAdmin(admin.ModelAdmin):
    """Manage user-to-role assignments."""
    list_display = ("user", "role", "organization", "assigned_at")
    list_filter = ("organization", "role")
    search_fields = ("user__username", "role__name", "organization__name")
    autocomplete_fields = ("user", "role", "organization")

    def organization(self, obj):
        return obj.organization
    organization.short_description = "Organization"
