from django.contrib import admin
from market.models import Market, MarketOption, UserBet


class MarketOptionInline(admin.TabularInline):
    model = MarketOption
    extra = 1
    fields = ["text", "position"]


@admin.register(Market)
class MarketAdmin(admin.ModelAdmin):
    list_display = ["title", "type", "status", "end_date", "created_by", "created_at"]
    list_filter = ["status", "type", "created_at"]
    search_fields = ["uuid", "title"]
    readonly_fields = [
        "uuid",
        "created_at",
        "updated_at",
        "created_by",
        "winning_option",
    ]
    inlines = [MarketOptionInline]
    fieldsets = (
        ("Info", {"fields": ["uuid", "title", "description"]}),
        ("Configuration", {"fields": ["type", "end_date"]}),
        ("Status", {"fields": ["status", "winning_option"]}),
        ("Metadata", {"fields": ["created_by", "created_at", "updated_at"]}),
    )

    def save_model(self, request, obj, form, change):
        if not change:  # Creating new market
            obj.created_by = request.user
        super().save_model(request, obj, form, change)

    @admin.action(description="Close selected markets")
    def close_markets(self, request, queryset):
        updated = queryset.filter(status=Market.Status.OPEN).update(
            status=Market.Status.CLOSED
        )
        self.message_user(request, f"Closed {updated} market(s).")

    actions = ["close_markets"]


@admin.register(MarketOption)
class MarketOptionAdmin(admin.ModelAdmin):
    list_display = ["text", "market", "position"]
    list_filter = ["market"]
    search_fields = ["uuid", "text", "market__title"]
    readonly_fields = ["uuid"]


@admin.register(UserBet)
class UserBetAdmin(admin.ModelAdmin):
    list_display = ["user", "option", "amount", "created_at"]
    list_filter = ["created_at", "option__market"]
    search_fields = ["uuid", "user__username", "option__text"]
    readonly_fields = ["uuid", "user", "option", "amount", "created_at", "updated_at"]

    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False
