# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.db import connection

from .models import PlatformAdmin


@admin.register(PlatformAdmin)
class PlatformAdminAdmin(UserAdmin):
    """
    Админка для управления администраторами платформы.

    Доступна только в public schema.
    """
    list_display = ('email', 'name', 'is_active', 'is_superuser', 'date_joined', 'last_login')
    list_filter = ('is_active', 'is_superuser', 'date_joined')
    search_fields = ('email', 'name')
    ordering = ('-date_joined',)

    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Персональные данные', {'fields': ('name',)}),
        ('Права доступа', {
            'fields': ('is_active', 'is_staff', 'is_superuser'),
            'description': 'Суперадмин может входить в /admin/ на tenant доменах для поддержки.'
        }),
        ('Важные даты', {'fields': ('last_login', 'date_joined')}),
    )

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'name', 'password1', 'password2', 'is_superuser'),
        }),
    )

    readonly_fields = ('date_joined', 'last_login')

    def has_module_permission(self, request):
        """Показывать только в public schema."""
        if hasattr(connection, 'schema_name') and connection.schema_name != 'public':
            return False
        return super().has_module_permission(request)

    def has_view_permission(self, request, obj=None):
        if hasattr(connection, 'schema_name') and connection.schema_name != 'public':
            return False
        return super().has_view_permission(request, obj)

    def has_add_permission(self, request):
        if hasattr(connection, 'schema_name') and connection.schema_name != 'public':
            return False
        return super().has_add_permission(request)

    def has_change_permission(self, request, obj=None):
        if hasattr(connection, 'schema_name') and connection.schema_name != 'public':
            return False
        return super().has_change_permission(request, obj)

    def has_delete_permission(self, request, obj=None):
        if hasattr(connection, 'schema_name') and connection.schema_name != 'public':
            return False
        return super().has_delete_permission(request, obj)
