from django.contrib import admin
from .models import SiteConfiguration, VATRate

# Register your models here.

@admin.register(SiteConfiguration)
class SiteConfigurationAdmin(admin.ModelAdmin):
    fieldsets = (
        ('Basic Information', {
            'fields': ('name', 'logo', 'favicon', 'currency')
        }),
        ('Contact Information', {
            'fields': ('contact_email', 'contact_phone', 'contact_address', 'opening_hours')
        }),
        ('Social Media', {
            'fields': ('facebook_url', 'instagram_url', 'youtube_url', 'tiktok_url', 'whatsapp_number')
        }),
        ('Shipping Settings', {
            'fields': ('zasilkovna_shipping_price', 'deutschepost_shipping_price', 'free_shipping_over')
        }),
        ('API Credentials', {
            'fields': ('zasilkovna_api_key', 'zasilkovna_api_password', 'deutschepost_client_id', 'deutschepost_client_secret', 'deutschepost_customer_ekp'),
            'classes': ('collapse',)
        }),
        ('Coupon Settings', {
            'fields': ('multiplying_coupons', 'addition_of_coupons_amount')
        }),
    )

@admin.register(VATRate)
class VATRateAdmin(admin.ModelAdmin):
    list_display = ('name', 'rate', 'is_default', 'is_active', 'description')
    list_filter = ('is_active', 'is_default')
    search_fields = ('name', 'description')
    list_editable = ('is_active',)
    
    def get_readonly_fields(self, request, obj=None):
        # Make is_default read-only in change form to prevent conflicts
        if obj:  # editing an existing object
            return ('is_default',) if not obj.is_default else ()
        return ()
    
    actions = ['make_default']
    
    def make_default(self, request, queryset):
        if queryset.count() != 1:
            self.message_user(request, "Select exactly one VAT rate to make default.", level='ERROR')
            return
        
        vat_rate = queryset.first()
        # Clear existing defaults
        VATRate.objects.filter(is_default=True).update(is_default=False)
        # Set new default
        vat_rate.is_default = True
        vat_rate.save()
        
        self.message_user(request, f"'{vat_rate.name}' is now the default VAT rate.")
    
    make_default.short_description = "Make selected VAT rate the default"
