from django.contrib import admin
from django.contrib.sites.models import Site
from django.contrib.sites.shortcuts import get_current_site
from .models import EmailConfiguration

@admin.register(EmailConfiguration)
class EmailConfigurationAdmin(admin.ModelAdmin):
    list_display = ('site', 'from_name', 'from_email', 'reply_to', 'updated_at')
    list_select_related = ('site',)
    search_fields = ('site__domain', 'from_name', 'from_email', 'reply_to')
    readonly_fields = ('created_at', 'updated_at')
    fieldsets = (
        (None, {
            'fields': ('site',)
        }),
        ('Email Settings', {
            'fields': (
                'api_key',
                ('from_name', 'from_email'),
                'reply_to'
            ),
            'description': 'Configure the email settings. The From field in emails will appear as "From Name <from@email.com>"'
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('site')

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "site":
            kwargs["queryset"] = Site.objects.all().order_by('domain')
        return super().formfield_for_foreignkey(db_field, request, **kwargs)
