from django.contrib import admin

from .models import Cart, CartItem, Coupon


@admin.register(Coupon)
class CouponAdmin(admin.ModelAdmin):
    list_display = ('code', 'discount_percent', 'min_purchase', 'active', 'valid_from', 'valid_to')
    list_filter = ('active',)
    search_fields = ('code',)


class CartItemInline(admin.TabularInline):
    model = CartItem
    extra = 0
    autocomplete_fields = ('product',)


@admin.register(Cart)
class CartAdmin(admin.ModelAdmin):
    list_display = ('user', 'created_at', 'updated_at', 'item_count', 'total_quantity')
    search_fields = ('user__username', 'user__email')
    inlines = (CartItemInline,)

    def item_count(self, obj):
        return obj.items.count()
    item_count.short_description = 'Items'

    def total_quantity(self, obj):
        return sum(i.quantity for i in obj.items.all())
    total_quantity.short_description = 'Total Qty'


@admin.register(CartItem)
class CartItemAdmin(admin.ModelAdmin):
    list_display = ('cart', 'product', 'quantity')
    search_fields = ('product__name', 'cart__user__username')
    autocomplete_fields = ('product',)
