"""
Django admin configuration for referrals app.
"""
from django.contrib import admin
from .models import ReferralCommission, ReferralEarning, ReferralProgramSettings


@admin.register(ReferralCommission)
class ReferralCommissionAdmin(admin.ModelAdmin):
    """
    Admin configuration for referral team levels.
    """
    list_display = ('level', 'required_members', 'bonus_amount', 'is_active', 'created_at')
    list_filter = ('is_active',)
    list_editable = ('required_members', 'bonus_amount', 'is_active')
    search_fields = ('=level',)
    fields = ('level', 'required_members', 'bonus_amount', 'is_active')


@admin.register(ReferralProgramSettings)
class ReferralProgramSettingsAdmin(admin.ModelAdmin):
    """
    Admin configuration for global referral program settings.
    """
    list_display = (
        'settings_name',
        'referrer_bonus_percentage',
        'referred_user_bonus_percentage',
        'minimum_deposit_amount',
        'maximum_deposit_amount',
        'updated_at',
    )
    list_editable = (
        'referrer_bonus_percentage',
        'referred_user_bonus_percentage',
        'minimum_deposit_amount',
        'maximum_deposit_amount',
    )
    readonly_fields = ('created_at', 'updated_at')
    fields = (
        'referrer_bonus_percentage',
        'referred_user_bonus_percentage',
        'minimum_deposit_amount',
        'maximum_deposit_amount',
        'created_at',
        'updated_at',
    )

    def has_add_permission(self, request):
        return not ReferralProgramSettings.objects.exists()

    def has_delete_permission(self, request, obj=None):
        return False

    @admin.display(description='Setting')
    def settings_name(self, obj):
        return 'Program Settings'


@admin.register(ReferralEarning)
class ReferralEarningAdmin(admin.ModelAdmin):
    """
    Admin configuration for ReferralEarning model.
    """
    list_display = (
        'user',
        'earning_type',
        'referred_user',
        'percentage_applied',
        'level_achieved',
        'amount',
        'deposit_amount',
        'is_credited',
        'created_at',
    )
    list_filter = ('is_credited', 'earning_type', 'level_achieved', 'commission')
    search_fields = ('user__username', 'referred_user__username')
    readonly_fields = ('created_at',)
