from django.contrib import admin
from .models import CommunicationCredits, CreditTransaction, ProxyPhoneNumber, MaskedSession


@admin.register(CommunicationCredits)
class CommunicationCreditsAdmin(admin.ModelAdmin):
    list_display = [
        'tenant',
        'balance_display',
        'auto_reload_enabled',
        'auto_reload_threshold_display',
        'last_twilio_sync_at',
    ]
    list_filter = ['auto_reload_enabled']
    search_fields = ['tenant__name']
    readonly_fields = [
        'total_loaded_cents', 'total_spent_cents',
        'last_twilio_sync_at', 'created_at', 'updated_at'
    ]

    def balance_display(self, obj):
        return f"${obj.balance_cents/100:.2f}"
    balance_display.short_description = 'Balance'

    def auto_reload_threshold_display(self, obj):
        return f"${obj.auto_reload_threshold_cents/100:.2f}"
    auto_reload_threshold_display.short_description = 'Reload Threshold'


@admin.register(CreditTransaction)
class CreditTransactionAdmin(admin.ModelAdmin):
    list_display = [
        'created_at',
        'credits',
        'amount_display',
        'transaction_type',
        'description',
    ]
    list_filter = ['transaction_type', 'created_at']
    search_fields = ['credits__tenant__name', 'description']
    readonly_fields = ['created_at']
    date_hierarchy = 'created_at'

    def amount_display(self, obj):
        sign = '+' if obj.amount_cents > 0 else ''
        return f"{sign}${obj.amount_cents/100:.2f}"
    amount_display.short_description = 'Amount'


@admin.register(ProxyPhoneNumber)
class ProxyPhoneNumberAdmin(admin.ModelAdmin):
    list_display = [
        'phone_number',
        'status',
        'assigned_tenant',
        'monthly_fee_display',
        'is_active',
    ]
    list_filter = ['status', 'is_active']
    search_fields = ['phone_number', 'assigned_tenant__name']
    readonly_fields = ['twilio_sid', 'created_at', 'updated_at']

    def monthly_fee_display(self, obj):
        return f"${obj.monthly_fee_cents/100:.2f}"
    monthly_fee_display.short_description = 'Monthly Fee'


@admin.register(MaskedSession)
class MaskedSessionAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'tenant',
        'status',
        'customer_phone',
        'staff_phone',
        'sms_count',
        'created_at',
        'expires_at',
    ]
    list_filter = ['status', 'created_at']
    search_fields = ['tenant__name', 'customer_phone', 'staff_phone']
    readonly_fields = ['created_at', 'updated_at']
    date_hierarchy = 'created_at'
