# core/admin.py
from django.contrib import admin
from .models import Branch, PromoCode, SiteConfiguration


@admin.register(Branch)
class BranchAdmin(admin.ModelAdmin):
    list_display = ("name", "code", "company", "is_active", "created_at")
    search_fields = ("name", "code")
    list_filter = ("is_active", "company")


@admin.register(PromoCode)
class PromoCodeAdmin(admin.ModelAdmin):
    list_display = ("code", "company", "discount_type", "discount_value", "is_active", "expires_at")
    list_filter = ("discount_type", "is_active", "company")
    search_fields = ("code",)

from .models import AIPrompt, AIChatLog

@admin.register(AIPrompt)
class AIPromptAdmin(admin.ModelAdmin):
    list_display = ("text", "company", "is_global", "created_at")
    list_filter = ("is_global", "company")
    search_fields = ("text",)

@admin.register(AIChatLog)
class AIChatLogAdmin(admin.ModelAdmin):
    list_display = ("user", "company", "created_at", "tokens_used")
    list_filter = ("company", "created_at")
    search_fields = ("prompt", "user__username")


@admin.register(SiteConfiguration)
class SiteConfigurationAdmin(admin.ModelAdmin):
    """
    Singleton admin — superadmin controls global platform settings here.
    Django Admin -> Site Configuration -> one row always shown.
    """
    fieldsets = (
        ("Payment Gateways", {
            "fields": (
                "active_payment_gateway",
                "manual_bank_name",
                "manual_account_number",
                "manual_account_name",
                "manual_payment_instructions",
                "manual_whatsapp_number",
            ),
            "description": (
                "Choose which gateway collects subscription payments. "
                "'Both' defaults to Monnify unless extended per company."
            ),
        }),
        ("WhatsApp / SMS (Global Master Switch)", {
            "fields": ("enable_whatsapp",),
            "description": (
                "This is the MASTER switch. Even if a company has WhatsApp enabled in their "
                "settings, it will NOT send unless this is ON. Turn on only when you have a "
                "valid API budget."
            ),
        }),
        ("Platform", {
            "fields": ("platform_name", "platform_logo_url", "maintenance_mode", "maintenance_message"),
        }),
        ("AI Limits", {
            "fields": ("ai_global_daily_limit",),
        }),
    )

    def has_add_permission(self, request):
        """Only one SiteConfiguration row allowed."""
        return not SiteConfiguration.objects.exists()

    def has_delete_permission(self, request, obj=None):
        return False  # Never delete the singleton

    def changelist_view(self, request, extra_context=None):
        """Redirect list to the single object edit page automatically."""
        from django.shortcuts import redirect
        obj = SiteConfiguration.get_solo()
        return redirect(f"/admin/core/siteconfiguration/{obj.pk}/change/")