from django.contrib import admin
from .models import Wallet, Transaction, Prediction, PredictionStake, Duel

@admin.register(Wallet)
class WalletAdmin(admin.ModelAdmin):
    list_display = ["user", "balance", "last_spin", "last_login_bonus"]
    search_fields = ["user__username"]
    ordering = ["-balance"]
    actions = ["award_100_points"]

    def award_100_points(self, request, queryset):
        for w in queryset:
            w.balance += 100
            w.save(update_fields=["balance"])
            Transaction.objects.create(wallet=w, amount=100, tx_type="admin_adjust", description="Admin bonus")
        self.message_user(request, f"Awarded 100pts to {queryset.count()} wallets.")
    award_100_points.short_description = "🎁 Award 100 bonus points"

@admin.register(Transaction)
class TransactionAdmin(admin.ModelAdmin):
    list_display = ["wallet", "amount", "tx_type", "description", "created_at"]
    list_filter = ["tx_type", "created_at"]
    search_fields = ["wallet__user__username", "description"]

@admin.register(Prediction)
class PredictionAdmin(admin.ModelAdmin):
    list_display = ["title", "creator", "status", "total_pool", "closes_at", "created_at"]
    list_filter = ["status", "category"]
    search_fields = ["title", "creator__username"]
    actions = ["settle_a", "settle_b", "cancel_refund"]

    def settle_a(self, request, queryset):
        for p in queryset.filter(status="open"):
            from wallet.views import _resolve_duel
            p.winning_option = "a"; p.status = "settled"; p.save()
        self.message_user(request, "Settled as Option A won.")
    settle_a.short_description = "Settle — Option A won"

    def settle_b(self, request, queryset):
        for p in queryset.filter(status="open"):
            p.winning_option = "b"; p.status = "settled"; p.save()
        self.message_user(request, "Settled as Option B won.")
    settle_b.short_description = "Settle — Option B won"

@admin.register(Duel)
class DuelAdmin(admin.ModelAdmin):
    list_display = ["id", "challenger", "opponent", "stake", "status", "winner", "created_at"]
    list_filter = ["status"]
    search_fields = ["challenger__username", "opponent__username"]
